package com.utopiaindustries.controller;

import com.utopiaindustries.auth.StitchingRole;
import com.utopiaindustries.model.ctp.JobCard;
import com.utopiaindustries.model.ctp.StitchingOfflineItem;
import com.utopiaindustries.service.*;
import com.utopiaindustries.util.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

@Controller
@StitchingRole
@RequestMapping( "/stitching" )
public class StitchingController {

    private final InventoryAccountService inventoryAccountService;
    private final JobCardService jobCardService;
    private final InventoryService inventoryService;
    private final BundleService bundleService;
    private final BarcodeService barcodeService;
    private final LocationService locationService;

    public StitchingController(InventoryAccountService inventoryAccountService, JobCardService jobCardService, InventoryService inventoryService, BundleService bundleService, BarcodeService barcodeService, LocationService locationService) {
        this.inventoryAccountService = inventoryAccountService;
        this.jobCardService = jobCardService;
        this.inventoryService = inventoryService;
        this.bundleService = bundleService;
        this.barcodeService = barcodeService;
        this.locationService = locationService;
    }

    @GetMapping
    public String homePage( Model model ){
        return "redirect:/stitching/receive-inventory";
    }

    @GetMapping( "/receive-inventory" )
    public String receiveInventoryForm( Model model ){
        // 2 for stitching
        model.addAttribute("accounts" , inventoryAccountService.findInventoryAccounts( 2L ) );
        model.addAttribute("cutPieceTypes", jobCardService.getAllPieceTypes() );
        return "/stitching/receive-inventory";
    }

    @PostMapping( "/receive-inventory" )
    public String receiveInventoryToCuttingAccount( RedirectAttributes redirectAttributes,
                                                    @RequestParam( "master-id" ) long masterId,
                                                    @RequestParam( "account-id" ) long accountId ){
        try {
            inventoryService.receiveInventoryFromMasterBarcode( masterId, accountId );
            redirectAttributes.addFlashAttribute("success", "Inventory Success Received" );
        } catch ( Exception ex ){
            redirectAttributes.addFlashAttribute("error", ex.getMessage() );
        }
        return "redirect:/stitching/receive-inventory";
    }

    /*
     *  get stitching inventory accounts
     * */
    @GetMapping( "/inventory-accounts" )
    public String getInventoryAccounts(  @RequestParam( value = "id", required = false ) String id,
                                         @RequestParam( value = "title", required = false) String title,
                                         @RequestParam( value = "active", required = false ) String active,
                                         @RequestParam( value = "created-by", required = false ) String createdBy,
                                         @RequestParam( value = "start-date", required = false ) String startDate,
                                         @RequestParam( value = "end-date", required = false ) String endDate,
                                         @RequestParam( value = "site-id", required = false ) String siteId,
                                         @RequestParam( value = "count", required = false ) Long count,
                                         Model model ) {
        // 2 for stitching


        model.addAttribute("accounts", inventoryAccountService.getInventoryAccounts(id, title, active, createdBy, startDate, endDate, siteId, count, "PROCESS", "2", false));
        model.addAttribute("locations", locationService.findAll() );
        if(count == null){
            return "redirect:/stitching/inventory-accounts?id=&title=&active=1&created-by=&start-date=&end-date=&site-id=&site-title=&count=100";
        }
        return "/stitching/inventory-accounts";
    }

    /*
    * get finished items
    * */
    @GetMapping( "/stitching-offline-items" )
    public String getStitchingOfflineItems( @RequestParam(value = "id", required = false ) String id,
                                            @RequestParam(value = "item-id", required = false ) String itemId,
                                            @RequestParam( value = "sku", required = false ) String sku,
                                            @RequestParam( value = "start-date", required = false) String startDate,
                                            @RequestParam( value = "end-date", required = false ) String endDate,
                                            @RequestParam( value = "job-card-id", required = false ) String jobCardId,
                                            @RequestParam( value = "count", required = false, defaultValue = "100") Long count,
                                            Model model
    ,RedirectAttributes redirect){
        LocalDate startDate1 = StringUtils.isNullOrEmpty(startDate) ? LocalDate.now().minusDays(30) : LocalDate.parse(startDate);
        LocalDate endDate1 = StringUtils.isNullOrEmpty(endDate) ? LocalDate.now() : LocalDate.parse(endDate);
        List<StitchingOfflineItem> itemList = bundleService.getStitchedOfflineItems( id, itemId, sku, startDate, endDate, jobCardId ,count );
        model.addAttribute("items", itemList ) ;
        model.addAttribute("startDate", startDate1);
        model.addAttribute("endDate", endDate1);
        return "/stitching/stitched-offline-items";
    }

    @GetMapping( "/create-stitching-items")
    public String createFinishItems( Model model ){
        model.addAttribute("accounts" , inventoryAccountService.findInventoryAccounts( 2L ) );
        model.addAttribute("jobCard", jobCardService.createNewJobCard() );
        return "/stitching/stitching-item-form";
    }

    @PostMapping( "/create-stitching-items" )
    public String createStitchedOfflineItems( @ModelAttribute JobCard jobCard,
                                               RedirectAttributes redirectAttributes,
                                               Model model ){
        try {
            inventoryService.createStitchingOfflineItemsFromJobCard( jobCard );
            redirectAttributes.addFlashAttribute("success", "Finished Item Created Successfully");
        } catch ( Exception exception ){
            exception.printStackTrace();
            redirectAttributes.addFlashAttribute( "error", exception.getMessage() );
        }
        return "redirect:/stitching/stitching-offline-items";
    }

    @PostMapping( "/generate-barcodes" )
    public Object generateBarcode(@RequestParam( name = "ids" ,required = false) Long[] ids,
                                          @RequestParam( name = "artifactType"  ) String artifactType, RedirectAttributes redirectAttributes ) throws Exception {
        if (ids == null){
            redirectAttributes.addFlashAttribute( "error", "Select At least One CheckBox" );
            return "redirect:/stitching/stitching-offline-items";
        }
        try {
            barcodeService.generateBarcodes( Arrays.asList( ids ), artifactType );
            redirectAttributes.addFlashAttribute( "success", "Barcode generated successfully" );
            return "redirect:/stitching/stitching-offline-items";
        }catch (Exception e){
            redirectAttributes.addFlashAttribute( "error", e );
            return "redirect:/stitching/stitching-offline-items";
        }
    }
}
