# Dispatches data to hasher and adds to database tables

import sqlalchemy
import os

from datetime import datetime
from flask_login import current_user

from .models import Hashchain, Art, List, TX 
from . import db

from app.lib import clean_file as cf
from app.lib import hasher as hsh

def mint(designated_fn, art_name, art_desc, min_price, buyout_price, close_date):
    # gen filehash
    filehash = hsh.hashfile(f'{cf.UPLOAD_FOLDER}/{designated_fn}')
    # gen txhash (if bought... or sold, or minted)
    ddt = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
    dt = sqlalchemy.func.now()
    txstring = f'[{filehash}, {ddt}, {current_user.id}, {current_user.id}, 0.0]' # minting
    txhash = hsh.gen_txhash(txstring)
    # fetch prev block hash OR GEN HASH
    try:
        prev_bhash = db.session.query(Hashchain).order_by(Hashchain.id.desc()).first().blockhash
        if prev_bhash is None:
            prev_bhash = hsh.GENESIS_HASH
    except:
        prev_bhash = hsh.GENESIS_HASH
    # gen block hash add to hashchain
    new_bhash = hsh.append_tx(txhash, prev_bhash)
    new_block = Hashchain(blockhash = new_bhash)
    db.session.add(new_block)
    # move the file into external secure storage (NOT DONE)
    os.rename(f'{cf.UPLOAD_FOLDER}/{designated_fn}', f'{cf.REPO_FOLDER}/{designated_fn}')
    # add to TX table (mint)
    new_tx = TX(
            filehash = filehash,
            datetime = dt,
            source_id = current_user.id,
            destination_id = current_user.id,
            price = 0.0,
            txhash = txhash
            )
    db.session.add(new_tx)
    # add to Art table
    new_art = Art(
            name = art_name,
            description = art_desc,
            filehash = filehash,
            owner = current_user.id,
            creator = current_user.id,
            dname = designated_fn
            )
    db.session.add(new_art)
    # add to List table
    new_listing = List(
            filehash = filehash,
            seller = current_user.id,
            min_price = min_price,
            out_price = buyout_price,
            timeout = close_date,
            )
    db.session.add(new_listing)

    db.session.commit() 

