package com.ease.gsms.server.controllers;

import com.ease.gsms.server.model.Dispatch;
import com.ease.gsms.server.model.DispatchStatus;
import com.ease.gsms.server.model.Message;
import com.ease.gsms.server.repositories.DispatchRepository;
import com.ease.gsms.server.services.DispatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

@Controller
public class MainController {

    @Autowired
    DispatchService dispatchService;

    @RequestMapping("/")
    public String index(@RequestHeader(value = "X-Requested-With", required = false) String requestedWith) {

        if ("com.ease.gsms".equals(requestedWith)) {

            return "redirect:/native-android-sender";

        } else {

            return "index";

        }

    }

    @RequestMapping("/download-android")
    public String downloadAndroid() {

        return "download-android";

    }

    @RequestMapping("/sms-creation/multi-sms")
    public String smsCreationMultiSms() {

        return "sms-creation/multi-sms";

    }

    @RequestMapping("/sms-creation/multi-excel")
    public String smsCreationMultiExcel() {

        return "sms-creation/multi-excel";

    }

    @RequestMapping("/dispatch/active")
    public String activeDispatches() {

        return "dispatches/active-dispatches";

    }

    @RequestMapping("/dispatch/device-list")
    public String deviceList() {

        return "devices/device-list";

    }

    @RequestMapping("/messages/list")
    public String messageList() {

        return "/messages/message-list";

    }

    @RequestMapping("/native-android-sender")
    public String nativeAndroidSender(HttpServletRequest request) {

        return "native/android/sender";

    }

    @Autowired
    private DispatchRepository dispatchRepository;

    @Autowired
    private JdbcTemplate template;

    @RequestMapping("/load-runner")
    @ResponseBody
    public String loadRunner(Principal principal) throws InterruptedException {

        int parallelWorkers = 4;

        BlockingQueue<Dispatch> dispatchQueue = new LinkedBlockingQueue<>(parallelWorkers);
        AtomicInteger mc = new AtomicInteger();

        for (int i=0; i<parallelWorkers; i++) {
            final int j = i;
            new Thread(){
                {
                    setDaemon(true);
                }
                public void run() {
                    for (;;) {
                        try {
                            Dispatch poll = dispatchQueue.take();
                            long t = System.currentTimeMillis();
                            dispatchRepository.saveRequest(poll);
                            System.out.println(j + ": " + poll + " - " + poll.getSubmissionDate() + " - " + mc.addAndGet(poll.getMessages().size()) + " - " + (System.currentTimeMillis() - t) + "ms");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }

//        template.execute("SET FILES LOG FALSE");

//        template.execute("CHECKPOINT");

        int messageCount = 10000; // every 3 days

        Calendar calendar = Calendar.getInstance();

        calendar.set(1996, Calendar.SEPTEMBER, 8, 12, 0, 0);

        int messageIndex = 1;

        while (calendar.getTime().getTime() < System.currentTimeMillis()) {

            Message[] messages = new Message[messageCount];

            for (int i=0; i<messageCount; i++) {

                messages[i] = new Message(String.format("0720%06d", i), "Message " + (messageIndex++));

                messages[i].setSendingStatus(1);
                messages[i].setSentDate(new Date(calendar.getTime().getTime() + i * 1000));
                messages[i].setDeliveryStatus(1);
                messages[i].setDeliveredDate(new Date(calendar.getTime().getTime() + (i + 1) * 1000));

            }

            Dispatch dispatch = new Dispatch(
                    null,
                    UUID.randomUUID(),
                    null,
                    principal.getName(),
                    calendar.getTime(),
                    calendar.getTime(),
                    false,
                    false,
                    true,
                    false,
                    false,
                    false,
                    false,
                    false,
                    0,
                    DispatchStatus.COMPLETED,
                    messages
            );

            dispatchQueue.put(dispatch);

            calendar.add(Calendar.DATE, 3);

        }

//        template.execute("SET FILES LOG TRUE");

//        template.execute("CHECKPOINT");

        return "OK";

    }

}
