package org.fool.glorious;

import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.fool.glorious.db.dao.RecordService;
import org.fool.glorious.db.entity.Record;
import org.fool.glorious.excel.ExcelServiceFactory;
import org.fool.glorious.excel.service.ExcelService;
import org.fool.glorious.utils.DirScanner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class DataProcessor {

    final private String name = "Excel Scanning Task";

    private Timer timer;

    @Autowired
    private RecordService recordService;

    @PostConstruct
    private void postConstruct() {
        timer = new Timer(name);
    }

    public void startTimerTask() {
        log.info(String.format("Scheduling timer task <%s>.", name));
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    insertData(getRecordsFromFiles(System.getProperty("filepath")));
                } catch (Exception e) {
                    log.warn("Errors occurred when an excel file was being processed.", e);
                }
            }
        }, TimeUnit.SECONDS.toMillis(10), TimeUnit.MINUTES.toMillis(1));
    }

    public void stopTimerTask() {
        timer.cancel();
        log.info(String.format("Timer task <%s> has been stopped.", name));
    }

    public void runTaskOnce() {
        insertData(getRecordsFromFiles(System.getProperty("filepath")));
    }

    private void insertData(List<Record> records) {
        log.info("Start inserting data into the database...");
        int skipped = 0;
        for (Record record : records) {
            recordService.insertRecord(record);
        }
        log.info(String.format("%d record(s) inserted.", records.size()));
    }

    private List<Record> getRecordsFromFiles(String arg) {
        log.info(String.format("Looking for Excel files under: <%s>.", arg));
        List<Record> records = new ArrayList();
        List<String> files = DirScanner.findAll(arg, new String[]{"xls", "xlsx"}, false);
        for (String file : files) {
            log.info(String.format("Extracting data from <%s>...", file));
            ExcelService es = ExcelServiceFactory.newInstance(file);
            List<List<String>> rows = es.traverseWorkbook(0);
            for (List<String> row : rows) {
                records.add(new Record(row.get(0), row.get(1), row.get(2), row.get(3), "", ""));
            }
        }
        log.info(String.format("%d record(s) found.", records.size()));
        return records;
    }
}
