var mongoose = require("mongoose");
const request = require('request-promise');
const AutoGenerator = mongoose.model("AutoGenerator");


const AWS = require('aws-sdk');
const ID = '';
const SECRET = '';
// The name of the bucket that you have created
const BUCKET_NAME = 'test-bucket';
const s3 = new AWS.S3({
    accessKeyId: ID,
    secretAccessKey: SECRET
});

async function addMerchantSubscribedProductCron(type = 4, module){ 
    if(!module){
        return false;
    }
    var limit = 1;  
    var csvRequest = await CsvUpload.find({ $and: [{"status": 0} , {"type" : type}]}).limit(parseInt(limit)).sort({'_id' :-1 }); 
    if(csvRequest.length > 0){ 
        var obj = {  
            status: 1 
        }  
        try { 
            const data = await CsvUpload.updateOne({"_id" : csvRequest['0']._id },{ $set: obj } , {upsert: false}); 
        } catch (err) { 
            console.log(err);
        } 
        var options = {
            uri: csvRequest[0].url,
            encoding: null
        };
        var merchantId = csvRequest[0].mId;
        request(options, async function(error, response, body) {
            if (error || response.statusCode !== 200) { 
                console.log("failed to get file");
                console.log(error);
            } else { 
                let csvData = await csv().fromString(body.toString());
                csvData = JSON.stringify(csvData);
                csvData = JSON.parse(csvData); 
                let upStatus = await merchantSubscribeList(module,csvData , merchantId);
                console.log(upStatus);
            }
        });
    }else{
        console.log('Merchant not subscribe any products');
    }
};
  
async function merchantSubscribeList(module,items,merchantId){
    if(!items || (items && !items.length))
      return false;
    let skus = items.map((item)=>{
      return item.Sku;
    });
    const products = await Products.find({'code' :{ $in: skus }}).exec();
    const productIds = products.map((produt)=>{
      return produt._id;
    });
    const alreadySubscribed = await module.find({$and:[{pId:{$in:productIds}},{mId:merchantId}]});
    const alreadySubscribedId = alreadySubscribed.map((item)=>{ 
      return item.pId;
    });
    const subscribeProducts = [];
    products.forEach((product)=>{
      const item = items.find((ele)=>ele.Sku == product.code);
      if(alreadySubscribedId.includes(product._id) !== -1 && item){
        subscribeProducts.push({ 
          mId     : merchantId, 
          pId     : product._id,
          margin  : item.Margin,
          dos     :  new Date(),
          dom     :  new Date(),
          am_status : 0,
          [mongooseConstantValues.IS_AMAZON_PRODUCT_UPLOADED]:item[mongooseConstantValues.IS_AMAZON_PRODUCT_UPLOADED]
        });
      }
    });
    const update = await module.insertMany(subscribeProducts);
    return update;
}

  async function upload_image(handle, callback) {
    var d = new Date();//
    const imageDir = "images/" + d.getFullYear().toString() + "/" + (d.getMonth() + 1).toString() + "/" + handle.handle  + "/";
    var s3dir = `${imageDir}`;
    var filename = Date.now().toString()+ makeid(6) +'.png';
    var options = {
        uri: handle.url,
        encoding: null
    };
    request(options, async function(error, response, body) {
        if (error || response.statusCode !== 200) { 
            console.log("failed to get image");
            console.log(error);
        } else { 
             var status = await uploadFile(body, s3dir + filename);             
        }   
    });
    callback(s3dir + filename);
  }
  
  async function uploadFile(file, key) {
    const params = {
        Bucket: process.env.S3_FILE_BUCKET,
        Key: key, // File name you want to save as in S3
        Body: file,
        ContentType : 'image/jpeg'
    };
    // Uploading files to the bucket
    s3.upload(params, async function(err, data) {
        if (err) {
            throw err;
        }  
    });
  };

  function makeid(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
       result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
  }

  async function getNextSequenceValue(sequenceName){
    try {
      const data = await AutoGenerator.findOne({id: sequenceName},{incNo:1,_id:0});
      if(!data){
        const sessionData = new AutoGenerator({
          id: sequenceName,
          incNo: 1000000,
        });
        await sessionData.save();
        return 1000000;
      }
      let incNo = data.incNo < 1000000 ? 1000000 : data.incNo+1;
      await AutoGenerator.updateOne({id: sequenceName},{$set:{incNo:incNo}});
      return incNo;
    } catch(err){
      throw err
    }
  }

  function messageBuilder(res, status, InputParams, msg, data = {}) {
    try {
        return res.status(status).json({
            InputParams,
            Response: { status, msg, ...data },
        });
    } catch (err) {
        throw err;
    }
  }

async function uploadExcel(file, key) {
    const params = {
        Bucket: process.env.S3_FILE_BUCKET,
        Key: key, // File name you want to save as in S3
        Body: file
    };
    // Uploading files to the bucket
    s3.upload(params, async function (err, data) {
        if (err) {
            throw err;
        }
        console.log(`File uploaded successfully. ${data.Location}`); 
        return true;
    });
};

  module.exports = { addMerchantSubscribedProductCron,upload_image,makeid,getNextSequenceValue,messageBuilder , uploadExcel}