from reggy.samples.models.basic_characters_info import BasicCharactersInfo
from reggy.samples.models.control_characters_info import ControlCharactersInfo
from reggy.samples.models.digits_info import DigitsInfo
from reggy.samples.models.list_of_literal_text_info import ListOfLiteralTextInfo
from reggy.samples.models.literal_text_info import LiteralTextInfo
from reggy.samples.models.match_anything_info import MatchAnythingInfo
from reggy.samples.models.numbers_info import NumbersInfo
from reggy.samples.models.unicode_characters_info import UnicodeCharactersInfo
from reggy.samples.models.back_reference_info import BackReferenceInfo
from reggy.samples.parser.samples import Samples
from reggy.samples.constants.control_characters import control_char_to_token, control_chars
from reggy.samples.constants.match_anything import basic_char_to_tok
from reggy.samples.tokens.repetition import Repetition
from reggy.samples.tokens import LiteralTextTok
from reggy.samples.constants.unicode_characters import unicode_chars, unicode_char_to_token
from reggy.samples.utils.regex_info_to_tok import regex_info_to_tok
from reggy.samples.utils.repetition_info_to_enum import repetition_info_to_enum
from reggy.samples.utils.digit_to_enum import digit_to_enum

class Parser:

    def __init__(self, regex_info):
        self._samples = Samples()
        self.nr_of_markers = 0
        self._parse_samples(regex_info)

    def get_parsed_samples(self):
        return self._samples

    def _parse_samples(self, regex_info):
        self._parse_general_regex_info(regex_info)

        for group in regex_info['sampleStringsInfo']:
            self._alternating_group = []

            for sample in group:
                self.nr_of_markers += 1
                marker_type = sample['markerType']

                if marker_type == 'Literal text':
                    self._parse_literal_text(sample)
                elif marker_type == 'Basic characters':
                    self._parse_basic_characters(sample)
                elif marker_type == 'Digits':
                    self._parse_digits(sample)
                elif marker_type == 'Control characters':
                    self._parse_control_characters(sample)
                elif marker_type == 'Unicode characters':
                    self._parse_unicode_characters(sample)
                elif marker_type == 'Match anything':
                    self._parse_match_anything(sample)
                elif marker_type == 'List of literal text':
                    self._parse_list_of_literal_text(sample)
                elif marker_type == 'Numbers':
                    self._parse_numbers(sample)
                elif marker_type == 'Backreference match of preceding marker':
                    self._parse_backreference(sample)

                self._insert_repeat_info(sample)

            self._samples.parsed_samples.append(self._alternating_group)

    def _parse_basic_characters(self, sample):
        marker_info = sample['markerInfo']
        self._alternating_group.append(BasicCharactersInfo(self.nr_of_markers,
                                                           marker_info))

    def _parse_literal_text(self, sample):
        marker_info = sample['markerInfo']

        extra_info = []
        if marker_info['caseInsensitive']:
            extra_info.append(LiteralTextTok.CASE_INSENSITIVE)
        else:
            extra_info.append(LiteralTextTok.CASE_SENSITIVE)

        if marker_info['matchAllExceptSpecified']:
            extra_info.append(LiteralTextTok.MATCH_ALL_EXCEPT_SPECIFIED)

        self._alternating_group.append(LiteralTextInfo(self.nr_of_markers,
                                                       sample['markedStrings'],
                                                       extra_info))

    def _parse_digits(self, sample):
        marker_info = sample['markerInfo']

        digits_info = DigitsInfo(self.nr_of_markers)
        for i in marker_info:
            if i != 'minus' and marker_info[i]:
                digits_info.digits.append(digit_to_enum[i])
            else:
                minus_info = marker_info['minus']

                digits_info.include_minus = minus_info['minus']
                digits_info.include_optional_minus = minus_info['optional']

        self._alternating_group.append(digits_info)

    def _parse_control_characters(self, sample):
        marker_info = sample['markerInfo']
        match_all_except_spec = marker_info['matchAllExceptSelectedOnes']

        wanted_control_chars = []
        for control_char in control_chars:
            if not match_all_except_spec and marker_info[control_char]:
                wanted_control_chars.append(control_char_to_token[control_char])
            elif match_all_except_spec and not marker_info[control_char]:
                wanted_control_chars.append(control_char_to_token[control_char])

        self._alternating_group.append(ControlCharactersInfo(self.nr_of_markers,
                                                             wanted_control_chars))

    def _parse_unicode_characters(self, sample):
        marker_info = sample['markerInfo']
        match_all_except_spec = marker_info['matchAllExceptSelectedOnes']

        wanted_unicode_chars = []
        for unicode_char in unicode_chars:
            if not match_all_except_spec and marker_info[unicode_char]:
                wanted_unicode_chars.append(unicode_char_to_token[unicode_char])
            elif match_all_except_spec and not marker_info[unicode_char]:
                wanted_unicode_chars.append(unicode_char_to_token[unicode_char])

        unicode_info = UnicodeCharactersInfo(self.nr_of_markers,
                                             wanted_unicode_chars,
                                             marker_info['individualCharacters'].split())

        self._alternating_group.append(unicode_info)

    def _parse_match_anything(self, sample):
        marker_info = sample['markerInfo']
        match_anything_info = MatchAnythingInfo(self.nr_of_markers)

        match_anything_except = marker_info['matchAnythingExcept']
        if match_anything_except == 'Specific characters':
            match_anything_info.specific_characters = ''.join(set(marker_info['specificCharacters']))
        elif match_anything_except == 'Specific character':
            match_anything_info.specific_character = marker_info['specificCharacter'][0]
        elif match_anything_except == 'Nothing':
            match_anything_info.nothing = True
        elif match_anything_except == 'Basic characters':
            basic_chars = marker_info['basicCharacters']
            match_anything_info.basic_characters = [basic_char_to_tok[i] for i in basic_chars.keys() if basic_chars[i]]

        match_anything_info.can_span_across_lines = marker_info['canSpanAcrossLines']
        match_anything_info.case_insensitive = marker_info['caseInsensitive']

        self._alternating_group.append(match_anything_info)

    def _parse_list_of_literal_text(self, sample):
        marker_info = sample['markerInfo']
        self._alternating_group.append(ListOfLiteralTextInfo(self.nr_of_markers,
                                                             marker_info['matchAnythingExceptSpecified'],
                                                             marker_info['literalText'],
                                                             marker_info['caseInsensitive']))

    def _parse_numbers(self, sample):
        marker_info = sample['markerInfo']
        self._alternating_group.append(NumbersInfo(self.nr_of_markers, marker_info))

    def _parse_backreference(self, sample):
        marker_info = sample['markerInfo']
        self._alternating_group.append(BackReferenceInfo(self.nr_of_markers, marker_info))

    def _parse_general_regex_info(self, regex_info):
        gen_re_info = regex_info['generalRegexInfo']

        self._samples.target     = regex_info_to_tok[gen_re_info['regexTarget']]
        self._samples.start_info = regex_info_to_tok[gen_re_info['startRegexMatchAt']]
        self._samples.end_info   = regex_info_to_tok[gen_re_info['endRegexMatchAt']]

    def _insert_repeat_info(self, sample):
        repeat_info = sample['repeatInfo']['repeat']

        curr = self._alternating_group[-1].repetition_info

        if repeat_info == 'Custom range':
            curr.repeat_info = Repetition.CUSTOM_RANGE
            curr.repeat_start = int(sample['repeatInfo']['start'])
            curr.repeat_end = int(sample['repeatInfo']['end'])
        elif repeat_info == 'n or more times':
            curr.repeat_info = Repetition.N_OR_MORE_TIMES
            curr.repeat_start = int(sample['repeatInfo']['start'])
        else:
            curr.repeat_info = repetition_info_to_enum[repeat_info]


import random
import socket
import sys

class Hex_Challenge:
    row_f = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0]
    row_l = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1]
    row_a = [1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1]
    row_g = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1]
    row_space = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    row_i = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0]
    row_s = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
    row_h = [1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1]
    row_e = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1]
    row_x = [1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1]
    numtostring = { 0 : "0", 1 : "1", 2 : "2", 3 : "3", 4 : "4", 5 : "5", 6 : "6", 7 : "7", 8 : "8", 9 : "9", 10 : "A", 11 : "B", 12 : "C", 13 : "D", 14 : "E", 15 : "F", }
    problem_type = { 0 : "addition", 1 : "subtraction", 2 : "multiplication", }
    min_length = 5
    fixedlength = 8

    def __init__(self, alpha_len=5, height=9, flag_len=3, symbol=15):
        self.hextable = []
        self.row_index = -1
        #funtion_type = { "addition" : plus(), "subtraction" : minus(), "multiplication" : multiply(), }
        self.answer_hex_string = []
        self.random_hex_string = []
        self.table_f = []
        self.table_l = []
        self.table_a = []
        self.table_g = []
        self.table_space = []
        self.table_i = []
        self.table_s = []
        self.table_h = []
        self.table_e = []
        self.table_x = []

        self.length = alpha_len
        self.height = height
        self.flaglength = flag_len
        self.symbol = symbol

        self.init_tab_r(self.table_f, self.row_f, self.symbol, self.length, self.height)
        self.init_tab_r(self.table_l, self.row_l, self.symbol, self.length, self.height)
        self.init_tab_c(self.table_a, self.row_a, self.symbol, self.length, self.height)
        self.init_tab_c(self.table_g, self.row_g, self.symbol, self.length, self.height)
        self.init_tab_r(self.table_space, self.row_space, self.symbol, self.length, self.height)
        self.init_tab_r(self.table_i, self.row_i, self.symbol, self.length, self.height)
        self.init_tab_c(self.table_s, self.row_s, self.symbol, self.length, self.height)
        self.init_tab_c(self.table_h, self.row_h, self.symbol, self.length, self.height)
        self.init_tab_r(self.table_e, self.row_e, self.symbol, self.length, self.height)
        self.init_tab_c(self.table_x, self.row_x, self.symbol, self.length, self.height)
        self.assign_hextable()

    def print_hextable(self, flaglen=3, fixedlen=8, length=5, height=9):
        for i in range(height):
            for j in range(flaglen+fixedlen):
                for k in range(length):
                    print(self.numtostring[self.hextable[i][j][k]]),
                print("0"),
            print("")

    def print_hex_row(self, hex_row):
        for i in range(len(hex_row)):
            print(self.numtostring[hex_row[i]]),
        print("")

    def create_hex_string(self, hex_row):
        hex_string = ""
        hex_list = []
        for i in range(len(hex_row)):
            hex_list.append(self.numtostring[hex_row[i]])
            #hex_string += numtostring[hex_row[i]]
        hex_string = ''.join(hex_list)
        #print hex_string
        return hex_string

    def print_rows(self, socket, bufferSize, height=9):
        all_correct = False
        key = -1
        for i in range(height):
            self.row_index = i
            for j in range(self.flaglength+self.fixedlength):
                self.hextable[i][j].append(0)
            self.reformat_hex_string(self.row_index, self.flaglength, self.fixedlength, self.length)
            hex_string = self.create_hex_string(self.answer_hex_string)
            answer = hex_string
            print("Answer to the question is: " + answer + ".")
            key = random.randint(0,1)
            if self.problem_type[key] == "addition":
                self.plus(self.row_index, self.length)
            elif self.problem_type[key] == "subtraction":
                self.minus(self.row_index, self.length)
            #self.funtion_type[problem_type[key]](self.row_index, self.length)
            if key == 0:
                hex_string = self.create_hex_string(self.answer_hex_string)
                socket.send(bytearray("Problem #" + str(i+1) + ":                           " +
                                    hex_string + "\r\n", "UTF-8"))

                hex_string = self.create_hex_string(self.random_hex_string)
                socket.send(bytearray("Please add the following hexadecimal: " +
                           hex_string + "\r\n", "UTF-8"))

            elif key == 1:
                hex_string = self.create_hex_string(self.answer_hex_string)
                if len(self.answer_hex_string) == 67:
                    socket.send(bytearray("Problem #" + str(i+1) + ":                               " +
                           hex_string + "\r\n", "UTF-8"))

                elif len(self.answer_hex_string) == 66:
                    socket.send(bytearray("Problem #" + str(i+1) + ":                                 " +
                           hex_string + "\r\n", "UTF-8"))

                hex_string = self.create_hex_string(self.random_hex_string)
                socket.send(bytearray("Please subtract the following hexadecimal: " +
                                      hex_string + "\r\n", "UTF-8"))

            socket.send(bytearray("Answer: ", "UTF-8"))
            del self.answer_hex_string[:]
            del self.random_hex_string[:]
            try:
                while True:
                    chunk = socket.recv(bufferSize)
                    chunk = chunk.decode("utf-8")
                    chunk = chunk[:-1]
                    #print("User's answer is " + chunk + ".")
                    #print(chunk)
                    if(answer == chunk):
                        all_correct = True
                        socket.send(bytearray("Correct!\r\n\r\n", "UTF-8"))
                        break
                    else:
                        all_correct = False
                        socket.send(bytearray("Incorrect, please give the correct answer.\r\n", "UTF-8"))
                        socket.send(bytearray(">", "UTF-8"))

            except IOError as e1:
                all_correct = False
                #print("Received keyboard interrupt from the user.")
                break

        if all_correct:
            socket.send(bytearray("Congratulation! All problems has been solved, did you manage to find the cookie?\r\n", "UTF-8"))
            socket.send(bytearray("Hint: it's in the answer(s)", "UTF-8"))
        else:
            return -1

        return 1

    def generate_hex_string(self, code, row_index, length):
        for i in range(len(self.hextable[row_index]) * (length + 1)):
            random_hex = random.randint(0, 15)
            if code == 0 and i == 0:
                random_hex = random.randint(0, 14)
            self.random_hex_string.append(random_hex)
        #print("random hex string")
        #print_hex_row(random_hex_string)
        #print

    def reformat_hex_string(self, row_index, flaglen=3, fixedlen=8, length=5):
        for i in range(flaglen+fixedlen):
            for j in range(length+1):
                self.answer_hex_string.append(self.hextable[row_index][i][j])
        #print("reformat string")
        #self.print_hex_row(self.answer_hex_string)
        #print

    def plus(self, row_index, length):
        code = 0
        self.generate_hex_string(code, row_index, length)
        for i in range((len(self.hextable[row_index]) * (length + 1)) - 1, -1, -1):
            if self.answer_hex_string[i] >= self.random_hex_string[i]:
                self.answer_hex_string[i] = self.answer_hex_string[i] - self.random_hex_string[i]
            elif self.answer_hex_string[i] < self.random_hex_string[i]:
                self.answer_hex_string[i-1] = self.answer_hex_string[i-1] - 1
                self.answer_hex_string[i] = self.answer_hex_string[i] + 16
                self.answer_hex_string[i] = self.answer_hex_string[i] - self.random_hex_string[i]
        #print("answer_hex_string")
        #print_hex_row(answer_hex_string)
        #print

    def minus(self, row_index, length):
        code = 1
        self.generate_hex_string(code, row_index, length)
        place_holder = -1
        for i in range((len(self.hextable[row_index]) * (length + 1)) - 1, -1, -1):
            place_holder = self.answer_hex_string[i] + self.random_hex_string[i]
            if i == 0 and place_holder > 15:
                self.answer_hex_string[i] = place_holder - 16
                self.answer_hex_string.insert(0,1)
            elif place_holder > 15:
                self.answer_hex_string[i] = place_holder - 16
                self.answer_hex_string[i-1] = self.answer_hex_string[i-1] + 1
            else:
                self.answer_hex_string[i] = place_holder

    def multiply(self, row_index, length):
        pass

    #funtion_type = { "addition" : plus, "subtraction" : minus, "multiplication" : multiply, }

    def assign_hextable(self, height=9):
        for i in range(height):
            self.hextable.append([])
            self.hextable[i].append(self.table_f[i])
            self.hextable[i].append(self.table_l[i])
            self.hextable[i].append(self.table_a[i])
            self.hextable[i].append(self.table_g[i])
            self.hextable[i].append(self.table_space[i])
            self.hextable[i].append(self.table_i[i])
            self.hextable[i].append(self.table_s[i])
            self.hextable[i].append(self.table_space[i])
            self.hextable[i].append(self.table_h[i])
            self.hextable[i].append(self.table_e[i])
            self.hextable[i].append(self.table_x[i])

    def init_tab_r(self, table, row, symbol, length=5, height=9):
        assign_value = 9
        for i in range(height):
            table.append([])
            for j in range(length):
                if j + 1 > self.min_length:
                    if assign_value < 5:
                        assign_value = random.randint(0,1)
                    table[i].append(assign_value)
                    break
                assign_value = row[i*self.min_length+j] * symbol
                if assign_value < 1:
                    assign_value = random.randint(0,1)
                table[i].append(assign_value)

    def init_tab_c(self, table, row, symbol, length=5, height=9):
        assign_value = 9
        for i in range(height):
            table.append([])
            for j in range(length):
                if length > self.min_length and j == (length / 2 + 1):
                    if assign_value < 5:
                        assign_value = random.randint(0,1)
                    table[i].append(assign_value)
                elif j + 1 > self.min_length:
                    break
                assign_value = row[i*self.min_length+j] * symbol
                if assign_value < 1:
                    assign_value = random.randint(0,1)
                table[i].append(assign_value)

    def print_table(self, table):
        for i in range(len(table)):
            print("the " + str(i) + " row is " + str(table[i]))


import curses
from curses import wrapper

def start_screen(stdscr):
    stdscr.clear()
    stdscr.addstr("Welcome to typing test!\n")
    stdscr.addstr("\nPress any key to begin")
    stdscr.refresh()
    stdscr.getkey()

def wpm_test(stdscr):
    target_text = "This is the test for typing test! please feel free to review the app"
    current_text = []

    stdscr.clear()
    stdscr.addstr(target_text)

    stdscr.refresh()
    stdscr.getkey()

def main(stdscr):
    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
    curses.init_pair(2, curses.COLOR_RED, curses.COLOR_RED)
    curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_RED)

    start_screen(stdscr)
    wpm_test(stdscr)
wrapper(main)


import requests
from bs4 import BeautifulSoup

def getText(a):
	Text = ""
	for each in a:
		Text = Text + " " + each.text.encode("utf-8").strip()
	return Text

a = BeautifulSoup(requests.get("https://www.google.co.in/search?q=MSFT&hl=en&gl=in&as_drrb=b&authuser=0&source=lnt&tbs=cdr%3A1%2Ccd_min%3A10%2F10%2F2011%2Ccd_max%3A10%2F10%2F2011&tbm=nws&&start=0").content, "lxml").select('.r a')
href = []
for each in a:
	href.append(each['href'][7:])

data = [['p', 'span', 'strong', 'b', 'pre', 'summary']]
for each in href:
	tags = []
	soup = BeautifulSoup(requests.get(each).content, "lxml")
	for tag in data[0]:
		tags.append(getText(soup.select(tag)))
	data.append(tags)
print(data)


"""
gde 4.2.2018
Adapted from Project Mesa Schelling Model example:
https://github.com/projectmesa/mesa-schelling-example/blob/master/analysis.ipynb
but changed to run stand-alone.
"""

import random
from SchellingAgent import SchellingAgent

class SchellingModel():
    '''
    Model class for the Schelling segregation model.
    '''

    def __init__(self, height, width, density, minority_pc):
        '''
        Create a new SchellingModel.

        height - rows in the city
        width - columns in the city
        density - share of cells that are occupied housing units
        minority_pc - share of agents that are of the minority type
        '''

        self.height = height
        self.width = width
        self.density = density
        self.minority_pc = minority_pc

        # set up an empty grid
        # 0 = empty, 1=minority agent, 2=majority agent
        self.grid = [[0] * self.height] * self.width

        # this is the list of all agents in the model
        self.agents = []

        # Set up agents
        for x in range(0,self.width):
            for y in range(0, self.height):
                if random.random() < self.density:
                    if random.random() < self.minority_pc:
                        agent_type = 1
                    else:
                        agent_type = 2

                    a = SchellingAgent((x, y), self.grid, agent_type)
                    self.agents.append(a)

    def print_status(self):
        '''
        Print relevant information about the current state of affairs.
        '''
        return('Implement print_status()')

    def step(self):
        '''
        Run one step of the model.  Let unhappy agents move to an empty square.
        '''
        print('Implement step')

    def run(self, max_iter=30):
        '''
        Runs all iterations of the model.
        max_iters - the maximum number of iterations to run.
        If All agents are happy, halt the model.
        '''
        print('Implement run')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# 一个.py文件就是一个模块
# 按目录组织模块，称为包
# 每一个包目录下必须有一个__init__.py 文件
# _xxx __xxx 这种是私有变量或函数的命名约定

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'a test module' # 表示模块的文档注释，任何模块代码的第一个字符串都被视为模块的文档注释；

__author__ = 'leighj' # 特殊变量

import sys

def test():
	args = sys.argv
	if len(args) == 1:
		print('hello world')
	elif len(args) == 2:
		print('hello %s' %args[1])
	else :
		print('Too many arguments')

if __name__ == '__main__':
	test()


from django.views import View
from django.http import HttpResponse,HttpResponseNotFound
from django.shortcuts import render
from django.urls import reverse
from django.http import JsonResponse

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt,csrf_protect

from django.contrib import messages

from django.db.models import Count

from django.shortcuts import redirect

import json
from django.core import serializers

#Models
from mission.models import Mission
from device.models import Device
from route.models import Location

import json

def get_dashboard(request):

    '''
    Display dashboard
    '''

    response=render(request, "index.html")
    return response

def get_mission_form(request):

    '''
    Return form to create missions
    '''

    response=render(request, "mission.html")
    return response

def get_recent_missions(request):

    '''
    Return the recent missions creatd by user
    '''
    try:
        missions=Mission.objects.all().reverse()[:10]
        mission_obj=[]

        for mission in missions:

            start_loc=[0,0]
            end_loc=[0,0]

            location=mission.locations.values()
            if location.exists():
                print(mission.locations.values())
                start_loc[0]=mission.locations.values()[0]['lat']
                start_loc[1]=mission.locations.values()[0]['long']
                end_loc[0]=mission.locations.values()[1]['lat'],
                end_loc[1]=mission.locations.values()[1]['long']
                name=mission.mission_name
                mission_obj.append({'name':name,'start':start_loc,'end':end_loc})

        context = {'missions': mission_obj }
        #response=render(request, "default.html",context)
        response=render(request, "route.html",context)
        return response

    except Mission.DoesNotExist():
        print('Not enough missions created')
        return JsonResponse({"mission_error":"Not enough missions"},status=200)

def get(request):

    '''
    Return the recent missions creatd by user
    '''

    try:
        mission=Mission.objects.values().reverse()[:10]
        return JsonResponse(mission,safe=False)

    except :
        print('Not enough missions created')
        return JsonResponse({"mission_error":"Not enough missions"},status=200)

def create_mission(request):

    '''
    Create new mission
    '''
    #Getting mission data from form details
    data = json.loads(request.body)
    print(data)

    mission_name = data['mission_name']
    #device_id    = data['device_id']
    date         = data['date']
    time         = data['time']

    mission=Mission(mission_name=mission_name,date=date,time=time)

    mission.save()
    print(mission)

        #Creating the locations, and adding to device
    location_list      =json.loads(data['locations'])
    print(location_list)
    for location in location_list:
        location_lat   = location['lat']
        location_lon   = location['long']

        location_obj=Location.objects.create(lat=location_lat,long=location_lon)
        print(location_obj)
        mission.locations.add(location_obj)

    return JsonResponse({"Mission created":mission.id},status=200)

def update_mission(request):

    '''
    Update mission given mission_id
    '''
    data = json.loads(request.body)

    mission_name            =   data['mission_name']
    mission_id              =   data['mission_id']
    device                  =   data['device_id']
    date                    =   data['date']
    time                    =   data['time']

    try:
        #Check if mission exists
        mission = Mission.objects.get(mission_id=mission_id)

        mission.mission_name=mission_name
        mission.device      =device
        mission.date        =date
        mission.time        =time

        print(mission)

        mission.save()

    except Mission.DoesNotExist:
        print('Mission not found')
        return jsonResponse({"Mission not found":mission_id},status=200)

def delete(request):

    '''
    Delete mission given mission_id
    '''

    mission_id=json.loads(request.body)['id']

    mission = Mission.objects.get(mission_id=mission_id)
    mission.delete()
    return JsonResponse({mission_id:" The mission is deleted "},status=200)


import networkx as nx
import matplotlib.pyplot as plt
from networkx.classes import graph

from readInstance import getInstance
from classes import Graph,Node,Edge

#myInstance = getInstance('inst4linearperturbacaoA')
#print(myInstance.weights)

def drawGraph():
    rgb_color = ['gray','r','g','b','y','m','brown']
    H = nx.Graph()
    for node in graph.nodes:
        H.add_node(node.name)
    for edge in graph.edges:
        u = edge.nodes[0].name
        v = edge.nodes[1].name
        color = edge.color
        H.add_edge(u,v,color=rgb_color[color])
    edges = H.edges()
    colors = [H[u][v]['color'] for u,v in edges]
    nx.draw(H, pos=nx.spring_layout(H),edge_color=colors, with_labels=True)
    plt.show()

def chain(v0,w):
    # Escolho uma cor para beta
    for beta_color in w.free_color:
        for vizinho in v0.neighbour:
            pass

    print(v0.free_color,w.free_color)

n = 5
G = nx.complete_graph(n)
graph = Graph()

# n cores disponiveis para cada no
all_colors = [x for x in range(1,n+1)]

for i in range (n):
    u = Node(i,set(all_colors))
    graph.nodes.append(u)

for edge in G.edges():
    u = graph.nodes[edge[0]]
    v = graph.nodes[edge[1]]
    edge = Edge(u,v)
    graph.edges.append(edge)
    u.neighbour.append(v)
    v.neighbour.append(u)

for edge in graph.edges:
    v0,w = edge.nodes
    common_color = v0.free_color.intersection(w.free_color)
    if common_color:
        color = common_color.pop()
        edge.color = color
        v0.free_color.remove(color)
        w.free_color.remove(color)
        #print(u.name,v.name)
    else:
        chain(v0,w)

# print(all_colors)
# for e in graph.edges:
#     print(e.nodes[0].name,e.nodes[1].name,'color:', e.color)
# for node in graph.nodes:
#     print('node:',node.name, node.free_color)
drawGraph()