const db = require("../models");
const TransactionHistory = db.transaction_history;
const Client = db.client;
const PurchaseHistory = db.purchase_history;
const PaymentType = db.payment_type;
const Exchange = db.exchange;
const Op = db.Sequelize.Op;

// Create and Save a new Tutorial
exports.create = (req, res) => {
  const transaction_history = {
    invoice_number	: req.body.invoice_number,
    client_id: req.body.client_id,
    date_of_purchase: req.body.date_of_purchase,
    type: req.body.type,
    wallet_address	: req.body.wallet_address	,
    amount_in_cad: req.body.amount_in_cad,
    purchasing_currency_id: req.body.purchasing_currency_id,
    live_rate: req.body.live_rate,
    available_crypto_amount: req.body.available_crypto_amount,
    fx_rate: req.body.fx_rate,
    fee_percentage: req.body.fee_percentage,
    fee_gained: req.body.fee_gained,
    amount_usdt: req.body.amount_usdt,
    amount: req.body.amount,
    trading_fee: req.body.trading_fee,
    network_fee: req.body.network_fee,	 
    payment_type_id: req.body.payment_type_id,	 
    exchange_use: req.body.exchange_use,	 
    payout_amount: req.body.payout_amount,	 
    payout_unit: req.body.payout_unit,	 
    other_fees: req.body.other_fees	 
  };

  // Save Tutorial in the database
  TransactionHistory.create(transaction_history)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Tutorial."
      });
    });
};


exports.findAll = (req, res) => {
  const title = req.query.title;
  const page = req.query.page;
  const type = req.query.type;
  var condition = title ? { title: { [Op.like]: `%${title}%` } } : null;
  var totalData = 0;
  var numberOfPages = 0;
  var numberOfRows = 10;
 
  TransactionHistory.count({
    where: condition
  })
  .then(function(count) {
    if(type == 1)
    {
        numberOfRows = count;
		var offSetCount = ((page-1)*numberOfRows);
		TransactionHistory.belongsTo(Client, {foreignKey: 'client_id'});
		TransactionHistory.belongsTo(PurchaseHistory, {foreignKey: 'purchasing_currency_id'});
		TransactionHistory.belongsTo(PaymentType, {foreignKey: 'payment_type_id'});
		TransactionHistory.belongsTo(Exchange, {foreignKey: 'exchange_use'});

		TransactionHistory.findAll({ where: condition,include: [Client,PurchaseHistory,PaymentType,Exchange],limit:numberOfRows,offset:offSetCount,order: [
				['id', 'DESC'],
			]})
			.then(data => {
			  var jsondata = {'data':data,'totalpage':numberOfPages,'currentpage':page-1};
			  res.send(jsondata);
			})
			.catch(err => {
			  res.status(500).send({
				message:
				  err.message || "Some error occurred while retrieving tutorials."
			  });
			});
    }
    else 
    {
        totalData = count;
		var offSetCount = ((page-1)*numberOfRows);
		numberOfPages = Math.ceil(totalData/numberOfRows);
		TransactionHistory.belongsTo(Client, {foreignKey: 'client_id'});
		TransactionHistory.belongsTo(PurchaseHistory, {foreignKey: 'purchasing_currency_id'});
		TransactionHistory.belongsTo(PaymentType, {foreignKey: 'payment_type_id'});
		TransactionHistory.belongsTo(Exchange, {foreignKey: 'exchange_use'});

		TransactionHistory.findAll({ where: condition,include: [Client,PurchaseHistory,PaymentType,Exchange],limit:numberOfRows,offset:offSetCount,order: [
				['id', 'DESC'],
			]})
			.then(data => {
			  var jsondata = {'data':data,'totalpage':numberOfPages,'currentpage':page-1};
			  res.send(jsondata);
			})
			.catch(err => {
			  res.status(500).send({
				message:
				  err.message || "Some error occurred while retrieving tutorials."
			  });
			});
    }

  });
  
  
};

exports.lastOne = (req, res) => {
  console.log("Hello");
  
  TransactionHistory.findOne({order: [
        ['id', 'DESC'],
    ]})
    .then(data => {
      if(data.id)
      {
        res.send({'data':data.id});
      } 
      else 
      {
        res.send({'data':0});
      } 
    })
    .catch(err => {
      res.status(500).send({
        message: "Error retrieving Transaction History with id=" + id
      });
    });
};
 
exports.findOne = (req, res) => {
  const id = req.params.id;

  TransactionHistory.findByPk(id)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message: "Error retrieving Transaction History with id=" + id
      });
    });
};

// Update a Tutorial by the id in the request
exports.update = (req, res) => {
  const id = req.params.id;
  const transaction_history = {
    invoice_number	: req.body.invoice_number,
    client_id: req.body.client_id,
    date_of_purchase: req.body.date_of_purchase,
    type: req.body.type,
    wallet_address	: req.body.wallet_address	,
    amount_in_cad: req.body.amount_in_cad,
    purchasing_currency_id: req.body.purchasing_currency_id,
    live_rate: req.body.live_rate,
    available_crypto_amount: req.body.available_crypto_amount,
    fx_rate: req.body.fx_rate,
    fee_percentage: req.body.fee_percentage,
    fee_gained: req.body.fee_gained,
    amount_usdt: req.body.amount_usdt,
    amount: req.body.amount,
    trading_fee: req.body.trading_fee,
    network_fee: req.body.network_fee,	 
    payment_type_id: req.body.payment_type_id,	 
    exchange_use: req.body.exchange_use,	 
    payout_amount: req.body.payout_amount,	 
    payout_unit: req.body.payout_unit,	 
    other_fees: req.body.other_fees	 
  };
  TransactionHistory.update(transaction_history, {
    where: { id: id }
  })
    .then(num => {
      if (num == 1) {
        res.send({
          message: "Transaction History was updated successfully."
        });
      } else {
        res.send({
          message: `Cannot update Transaction History with id=${id}. Maybe Transaction History was not found or req.body is empty!`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Error updating Transaction History with id=" + id
      });
    });
};

// Delete a Tutorial with the specified id in the request
exports.delete = (req, res) => {
  const id = req.params.id;

  TransactionHistory.destroy({
    where: { id: id }
  })
    .then(num => {
      if (num == 1) {
        res.send({
          success:true,
          message: "Transaction History was deleted successfully!"
        });
      } else {
        res.send({
          success:false,
          message: `Cannot delete Client with id=${id}. Maybe Client was not found!`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        success:false,
        message: "Could not delete Transaction History with id=" + id
      });
    });
};
 
