const fastify = require("fastify")({
    logger: true,
  });
const boom = require("boom");
const customJwtAuth = require("../customAuthJwt");

const bcrypt = require("bcrypt");
const saltRounds = 10;



//Get the data models
const { Supplier ,ProfilePicture, generateSupplierId, DeliveryBoy} = require('../models/supplier');


async function bcryptPassword(password) {
    encryptedPwd = bcrypt.hash(password, saltRounds);
    return encryptedPwd;
}

async function bcryptComparePassword(pwd, encpassword) {
    isSame = bcrypt.compare(pwd, encpassword);
    return isSame;
}
  


//Supplier Login Controller

exports.loginSupplier = async (req) => {
    try {
      const phone = req.body.phone;
      const password = req.body.password;
      
      const supplier = await Supplier.findOne({ phone: phone });
      // compare supplier password with what is supplied
      if (supplier) {
        isSame = await bcryptComparePassword(
          password,
          supplier.services.password.bcrypt
        );
        // if password supplied matches return object
        if (isSame) {
          return { same: true, supplier: supplier };
        } else {
          return { same: false };
        }
      } else {
        return { same: false };
      }
    } catch (err) {
      throw boom.boomify(err);
    }
  };
  



//DeliveryBoy Login Controller


exports.loginDeliveryBoy = async (req) => {
  try {
    const phone = req.body.phone;


    const delivery = await DeliveryBoy.findOne({ phone: phone });


      if (delivery) {
        return { same: true, delivery: delivery };
      } else {
        return { same: false };
      }
   
  } catch (err) {
    throw boom.boomify(err);
  }
};

  exports.addSupplier = async (req, reply) => {
    try {
    //  await resetCounter();//to set customer id back to 0
    var s_id = await generateSupplierId()
    var building= ((req.body.suppliername).slice(0, 3)).toUpperCase();
    var supplier_id = `AWSS${building}${s_id}`
      // console.log("This is the reply in the handler after the validations", reply);
      s_data = {   
        supplierId: supplier_id,
        suppliername: req.body.suppliername,
        emails: req.body.emails,
        password: req.body.password,
        phone: req.body.phone,
        description: req.body.description,
        profile: {
          firstName: req.body.firstName,
          lastName: req.body.lastName,
          contactNumber: req.body.phone,
          alternativeContactNumber: req.body.alternativeContactNumber,
          office_address: req.body.office_address,
          country: req.body.country,
          state: req.body.state,
          city: req.body.city,
          office_adress: req.body.office_adress,
          zip: req.body.zip,
        },
        latitude: req.body.latitude,
        longitude: req.body.longitude,
        fcmId : req.body.fcmId
      };
      
      var supplier = new Supplier(s_data);
  
      //password is not at the top level in the collection.
      supplierpass = req.body.password;
  
      // If fields are sent via form encoding , capture the fields and assign them to the supplier Object.
  
      checkFormEncoding = isSupplierFormUrlEncoded(req);
      if (checkFormEncoding.isSupplierFormUrlEncoded) {
        suppliertobeInserted = checkFormEncoding.supplier;
        console.log("thsi true url string");  
        supplier.suppliername = suppliertobeInserted.suppliername;
        supplier.firstName = suppliertobeInserted.firstName;
        supplier.lastName = suppliertobeInserted.lastName;
        supplier.phone = suppliertobeInserted.phone;
        supplier.emails = suppliertobeInserted.emails;
        supplier.passsword = suppliertobeInserted.password;
        supplier.supplierId = suppliertobeInserted.supplier_id;
        supplier.office_adress = suppliertobeInserted.office_adress;
        supplier.alternativeContactNumber = suppliertobeInserted.alternativeContactNumber;
        supplier.latitude = suppliertobeInserted.latitude;
        supplier.longitude = suppliertobeInserted.longitude;
        supplier.fcmId = suppliertobeInserted.fcmId
        supplier.description = suppliertobeInserted.description
      }
  
      
      console.log("---------checkurl ecnoded string-----------------------");
  
      // Store hash in your password DB.
      hash = await bcryptPassword(supplierpass);
  
      if (hash) {
        supplier.services.password.bcrypt = hash;
        if (req.body.role) {
          supplier.profile.role = req.body.role;
          console.log("******************************************************");
          console.log(supplier);
        } else {
          role = ["supplier"];
          supplier.profile.role = role;
        }

        insertedSupplier = await supplier.save();
        console.log(insertedSupplier);
        if (insertedSupplier) {
          // Prepare supplier object and wrap it inside the armintatankdata
          var retSupplier = {
            armintatankdata: {
              suppliername: insertedSupplier.suppliername,
              phone: insertedSupplier.phone,
              supplierId: insertedSupplier.supplierId,
              office_adress: insertedSupplier.office_adress,
              emails: [
                {
                  email: insertedSupplier.emails[0].email,
                },
              ],
              profile: insertedSupplier.profile,
              latitude: insertedSupplier.latitude,
              longitude: insertedSupplier.longitude,
              fcmId : insertedSupplier.fcmId,
              description : insertedSupplier.description
            },
            status_code: 200,
          };
  
          return retSupplier;
        }
      }
    } catch (err) {
      throw boom.boomify(err);
    }
  };

  exports.editCuurentSupplierInfo = async (req, reply) => {
    try {
      const { supplierId } = req.params;
      const supplierInfo = await Supplier.findOne({ supplierId: supplierId.toString() });
      const updateData = req.body;
  
      if (updateData.firstName) supplierInfo.profile.firstName = updateData.firstName;
      if (updateData.lastName) supplierInfo.profile.lastName = updateData.lastName;
      if (updateData.suppliername) supplierInfo.suppliername = updateData.suppliername;
      if (updateData.phone) supplierInfo.profile.contactNumber = updateData.phone;
      if (updateData.office_address) supplierInfo.profile.office_address = updateData.office_address;
      if (updateData.alternativeContactNumber) supplierInfo.profile.alternativeContactNumber = updateData.alternativeContactNumber;
      if (updateData.city) supplierInfo.profile.city = updateData.city;
      if (updateData.state) supplierInfo.profile.state = updateData.state;
      if (updateData.country) supplierInfo.profile.country = updateData.country;
      if (updateData.zip) supplierInfo.profile.zip = updateData.zip;
       if (updateData.phone) supplierInfo.phone = updateData.phone;
       if (updateData.description) supplierInfo.description = updateData.description;
       if (updateData.startingPrice) supplierInfo.startingPrice = updateData.startingPrice;
       if (updateData.status) supplierInfo.status = updateData.status;
      if (updateData.emails) supplierInfo.emails = updateData.emails;
      console.log(supplierInfo.emails[0].email)
      if (updateData.role) supplierInfo.profile.role = updateData.role;
      
      if (updateData.phone) {
        const phoneNumber =  updateData.phone //libphonenumberjs.parsePhoneNumber(updateData.phone);
        if (phoneNumber) {
          // access returned collection
          if (!phoneNumber) {                     //if (!phoneNumber.isValid()) {
            error = {
              armintatankdata: {
                error: true,
                code: 10002,
                message:
                  "10002 - Phone # " +
                  updateData.phone +
                  " is not a valid phone number",
              },
            };
            req.body.regError = error;
            reply.status(406).send(error);
          }
        }
      }
  
      if (supplierInfo.phone == updateData.phone) {
        console.log("IF++++++++++++++=");
        supplierInfo.phone = updateData.phone;
        supplierInfo.phoneVerified = true;
      } else {
        console.log("Ilse++++++++++++++=");
        supplierInfo.phone = updateData.phone;
        supplierInfo.phoneVerified = false;
      }
      const supplier = await supplierInfo.save();
      return supplier;
    } catch (err) {
      throw boom.boomify(err);
    }
  };
  