const mongoose = require("mongoose");
const WInward = mongoose.model("WInward");
const LastMileTracking = mongoose.model("LastMileTracking");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const moment = require('moment-timezone');
const { webAPiValidation } = require("../handlers/webValidation");
const request = require('request-promise');
const axios = require('axios');
	
exports.getTrackings = async (req,res) => {
		const countOrdData = await WInward.find({trackingId:{ $exists: true, $ne: null },deleivered_date:null,cancel_before_dispatch:null,refund_date:null });
		let currentPage = 1;
		const itemsPerPage = 50; // Number of items per page
		const totalItems = countOrdData.length;
		
		//console.log(totalItems);return false;
		do {
			const skip = (currentPage - 1) * itemsPerPage;
			if ((currentPage - 1) * itemsPerPage < totalItems) {
				const ordSerData = await WInward.find({trackingId:{ $exists: true, $ne: null },deleivered_date:null,cancel_before_dispatch:null,refund_date:null }).skip(skip).limit(itemsPerPage);
				currentPage++;
				console.log(currentPage,itemsPerPage,totalItems);
				let productArray=[];
				for(const key of Object.keys(ordSerData)){
					let itemRow = ordSerData[key];
					productArray.push({
						[key]:itemRow.trackingId.toString(),
					})
				};
				let awbArray = productArray.map(obj => {
					let value = Object.values(obj)[0];
					let transformedValue = value;
					return transformedValue;
				});

				//console.log(JSON.stringify(awbArray));return false;
				
				let data = JSON.stringify({
				  "email": "ashutosh.singh@shopperr.in",
				  "password": "Ashu@9305"
				});
				
				
				var config = {
				  method: 'post',
				  maxBodyLength: Infinity,
				  url: 'https://apiv2.shiprocket.in/v1/external/auth/login',
				  headers: { 
					'Content-Type': 'application/json'
				  },
				  data : data
				};

				axios(config)
				.then(function (response) {
				  //console.log(response.data.token);
				  var token = response.data.token;
				  
				  //console.log(AwbArray);return false;
				  
				  var data = JSON.stringify({
					  "awbs": awbArray
					});
				  // console.log(data);
				   
					var configTrack = {
					  method: 'post',
					maxBodyLength: Infinity,
					  url: 'https://apiv2.shiprocket.in/v1/external/courier/track/awbs',
					  headers: { 
						'Content-Type': 'application/json', 
						'Authorization': `Bearer ${token}`
					  },
					  data : data
					};

					axios(configTrack)
					.then(async function (response) {
						
						let resArray=[];
						for(const key of Object.keys(response.data)){
							let itemRow = response.data[key];
							
							var fetchAwb = await WInward.findOne({ trackingId: [key]});
							//console.log(itemRow.tracking_data);return false;
							let ordStatus = fetchAwb.order_status;
							
							  if(itemRow.tracking_data.shipment_track[0].current_status == 'Delivered'){
								ordStatus = 3
							  }
							   //console.log(order.trackingId.toString());
							  let updateInward = {
								order_status: ordStatus,
								last_update: new Date(),
								deleivered_date: itemRow.tracking_data.shipment_track[0].delivered_date,
								couriorPartnerappweight: itemRow.tracking_data.shipment_track[0].weight
								};
								 //console.log(updateInward);
								await WInward.updateOne({trackingId:fetchAwb.trackingId.toString()}, { $set: updateInward });
								
								var lmsTrackingData = await LastMileTracking.find({ s_orderno: fetchAwb.s_orderno});
								//console.log(lmsTrackingData.length);return false;
								if(lmsTrackingData.length > 0){
									//db.collection.remove(query);
									await LastMileTracking.deleteOne({s_orderno: fetchAwb.s_orderno});
									const LastMileTrackingData = {
										s_orderno: fetchAwb.s_orderno,
										mkpOrderId: fetchAwb.mkpOrderId,
										track_status: itemRow.tracking_data.track_status,
										shipment_status: itemRow.tracking_data.shipment_status,
										shipment_track: itemRow.tracking_data.shipment_track,
										shipment_track_activities: itemRow.tracking_data.shipment_track_activities
									};
									await LastMileTracking.create(LastMileTrackingData);
								} else {
									const LastMileTrackingData = {
										s_orderno: fetchAwb.s_orderno,
										mkpOrderId: fetchAwb.mkpOrderId,
										track_status: itemRow.tracking_data.track_status,
										shipment_status: itemRow.tracking_data.shipment_status,
										shipment_track: itemRow.tracking_data.shipment_track,
										shipment_track_activities: itemRow.tracking_data.shipment_track_activities
									};
									await LastMileTracking.create(LastMileTrackingData);
								}
						};
						
					  //console.log(resArray);
					
						//return false;
					  
					  
					  
					  //console.log(response.data.tracking_data.shipment_track_activities);
					  
					})
					.catch(function (error) {
					  console.log(error);
					});


				})
				.catch(function (error) {
				  console.log(error);
				});
			}
			
		} while (currentPage <= totalItems);

	return false;
		
};
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
