import logging
import scipy.fftpack as sfft
from plotter import Plotter
from scipy import signal
from cache import timeit
from extractors import Rect_Evaluator
import tqdm
from lattices import SCC_Lattice, VO2_Lattice, VO2_New
import sys
from spin_image import SpinImage
import numpy as np
import matplotlib.pyplot as plt
plt.style.use(["style", "colors", "two_column"])
logger = logging.getLogger('fft')
# logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)


def ising(file, num):
    LEN = 150
    #lat = VO2_New(LEN, LEN)
    lat = VO2_New(LEN, LEN)
    rect = Rect_Evaluator(lat.get_spots())

    out_rect = [[] for x in range(4)]
    percentage = []
    weighted_percentage = []
    si = SpinImage(lat.get_phases())
    already_inited = False

    spins = np.load(file)["s1"]
    spins[spins==-1] = 0

    for i in tqdm.tqdm(range(500)):

        (ix,iy) = np.random.randint(2000-LEN-LEN,size=2)
        maske = spins[ix:ix+2*LEN, iy:iy+2*LEN]

        si.apply_mask(lat.parse_mask(maske))
        si.gaussian(LEN)

        intens = si.fft()
        if not already_inited:
            rect.generate_mask(intens, merge=True)
            already_inited = True

        ir, vr = rect.extract(intens)
        for lis, val in zip(out_rect, vr):
            lis.append(val)
        percentage.append(np.sum(maske))
        [p1, p2] = si.get_intens(lat.parse_mask(maske))
        weighted_percentage.append(p1/(p1+p2))
        np.savez(f"ising_rect_{num}_temp.npz",
             w_percentage=weighted_percentage, percentage=percentage, out_1=out_rect[0],
             out_2=out_rect[1], out_3=out_rect[2], out_4=out_rect[3])

    percentage = np.array(percentage)
    weighted_percentage = np.array(weighted_percentage)
    percentage /= np.max(percentage)

    np.savez(f"ising_rect_{num}.npz",
             w_percentage=weighted_percentage, percentage=percentage, out_1=out_rect[0],
             out_2=out_rect[1], out_3=out_rect[2], out_4=out_rect[3])

def runner(file, idx):
    np.random.seed(1234)
    print(f"runnig: {file}")
    ising(file,idx)


if __name__ == "__main__":
    files = sys.argv[2:]
    idx = int(sys.argv[1])
    print(f"{idx}/{len(files)}")
    if idx > len(files):
        exit()
    if idx < 1:
        exit()
    runner(files[idx-1], idx)
