#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 13 00:15:21 2017

@author: rongdilin
"""
import numpy as np
import sys
import subprocess
import os
from tex import latex2pdf

class Sudoku(object):
    def __init__(self, file):
        try:
            self.state = 0
            self.whole = []
            self.dm = np.loadtxt(file, 'int')
            #print self.dm
            self.dl = np.loadtxt(file, 'int').tolist()
            
            if np.shape(self.dm) != (9,9):
                raise ValueError
        except ValueError:
            print('sudoku.SudokuError: Incorrect input.\n');
            sys.exit();        
    
    def __str__(self):
        return str(self.dl);
        
    def preassess(self):
        try:
            
            for line in self.dl:
                if any(x !=0 and line.count(x) > 1 for x in line):
                    raise ValueError;
                for item in line:
                    if item not in list(range(0,10)):
                        raise ValueError;
                    self.whole.append(item)
            check = np.matrix.copy(self.dm).T
            checkl = check.tolist()
            for line1 in checkl:
                if any(x != 0 and line1.count(x) > 1 for x in line1):
                    raise ValueError
            #box contains 9 3*3 box
            #which is ordered in horizontal
            box = []
            for i in range(0,9,3):
                for j in range(0,9,3):
                    sub = self.dl[i][j:j+3]
                    sub.extend(self.dl[i+1][j:j+3])
                    sub.extend(self.dl[i+2][j:j+3])
                    box.append(sub)
                    #print sub
                if any(x != 0 and sub.count(x) > 1 for x in sub):
                    raise ValueError
            print('There might be a solution.');
        except ValueError:
            print('There is clearly no solution.');
            sys.exit();
 
    def bare_tex_output(self):
        # output the sudoku in the tex style
        tex_file = []
        tex_file = self.latex_header() + self.latex_table() + self.latex_footer();
        #print(tex_file)
        with open('test.tex', 'w') as fout:
            for i in range(len(tex_file)):
                fout.write(tex_file[i])
                
        #subprocess.call(["/usr/local/texlive/2017basic/bin/x86_64-darwin/pdfTex","test.tex"])
#        document = ur"""
#        \documentclass[10pt]{article}
#        \\usepackage[left=0pt,right=0pt]{geometry}
#        \\usepackage{tikz}
#        \\usetikzlibrary{positioning}
#        \\usepackage{cancel}
#        \pagestyle{empty}
#        
#        \newcommand{\N}[5]{\tikz{\node[label=above left:{\tiny #1},
#                                       label=above right:{\tiny #2},
#                                       label=below left:{\tiny #3},
#                                       label=below right:{\tiny #4}]{#5};}}
#        
#        \begin{document}
#        
#        \tikzset{every node/.style={minimum size=.5cm}}
#        
#        \begin{center}
#        \begin{tabular}{||@{}c@{}|@{}c@{}|@{}c@{}||@{}c@{}|@{}c@{}|@{}c@{}||@{}c@{}|@{}c@{}|@{}c@{}||}\hline\hline
#        % Line 1
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{1} &
#        \N{}{}{}{}{9} & \N{}{}{}{}{} & \N{}{}{}{}{} &
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{8} \\ \hline
#        % Line 2
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{7} &
#        \N{}{}{}{}{} & \N{}{}{}{}{6} & \N{}{}{}{}{} &
#        \N{}{}{}{}{1} & \N{}{}{}{}{} & \N{}{}{}{}{} \\ \hline
#        % Line 3
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{7} &
#        \N{}{}{}{}{} & \N{}{}{}{}{6} & \N{}{}{}{}{} &
#        \N{}{}{}{}{1} & \N{}{}{}{}{} & \N{}{}{}{}{} \\ \hline\hline
#        % Line 4
#        \N{}{}{}{}{} & \N{}{}{}{}{3} & \N{}{}{}{}{4} &
#        \N{}{}{}{}{} & \N{}{}{}{}{9} & \N{}{}{}{}{} &
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{} \\ \hline
#        % Line 5
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{} &
#        \N{}{}{}{}{5} & \N{}{}{}{}{} & \N{}{}{}{}{4} &
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{} \\ \hline
#        % Line 6
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{} &
#        \N{}{}{}{}{} & \N{}{}{}{}{1} & \N{}{}{}{}{} &
#        \N{}{}{}{}{4} & \N{}{}{}{}{2} & \N{}{}{}{}{} \\ \hline\hline
#        % Line 7
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{5} &
#        \N{}{}{}{}{} & \N{}{}{}{}{7} & \N{}{}{}{}{} &
#        \N{}{}{}{}{9} & \N{}{}{}{}{} & \N{}{}{}{}{} \\ \hline
#        % Line 8
#        \N{}{}{}{}{} & \N{}{}{}{}{1} & \N{}{}{}{}{} &
#        \N{}{}{}{}{8} & \N{}{}{}{}{4} & \N{}{}{}{}{} &
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{7} \\ \hline
#        % Line 9
#        \N{}{}{}{}{7} & \N{}{}{}{}{} & \N{}{}{}{}{} &
#        \N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{9} &
#        \N{}{}{}{}{2} & \N{}{}{}{}{} & \N{}{}{}{}{} \\ \hline\hline
#        \end{tabular}
#        \end{center}
#        
#        \end{document}
#                
#        """
        document = ur"""
        \documentclass{article}
        \begin{document}
        Hello, World!
        \end{document}
        """
        pdf = latex2pdf(document)
    
    def latex_table(self):
        mid = ("% Line 1\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{1} &\n"
        "\N{}{}{}{}{9} & \N{}{}{}{}{} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{8} \\\ \hline\n"
        "% Line 2\n" +
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{7} &\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{6} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{1} & \N{}{}{}{}{} & \N{}{}{}{}{} \\\ \hline\n"
        "% Line 3\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{7} &\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{6} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{1} & \N{}{}{}{}{} & \N{}{}{}{}{} \\\ \hline\hline\n"
        "% Line 4\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{3} & \N{}{}{}{}{4} &\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{9} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{} \\\ \hline\n"
        "% Line 5\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{5} & \N{}{}{}{}{} & \N{}{}{}{}{4} &\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{} \\\ \hline\n"
        "% Line 6\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{1} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{4} & \N{}{}{}{}{2} & \N{}{}{}{}{} \\\ \hline\hline\n"
        "% Line 7\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{5} &\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{7} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{9} & \N{}{}{}{}{} & \N{}{}{}{}{} \\\ \hline\n"
        "% Line 8\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{1} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{8} & \N{}{}{}{}{4} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{7} \\\ \hline\n"
        "% Line 9\n"
        "\N{}{}{}{}{7} & \N{}{}{}{}{} & \N{}{}{}{}{} &\n"
        "\N{}{}{}{}{} & \N{}{}{}{}{} & \N{}{}{}{}{9} &\n"
        "\N{}{}{}{}{2} & \N{}{}{}{}{} & \N{}{}{}{}{} \\\ \hline\hline\n");
        #print mid
        return mid
#        for r in range(0, 9): # row
#            print("\n%% Line %d\n" % (r + 1));
#            for c in range(0, 9): # column
#                print("\\N")
#                if self.state:
#                    # Print the marks in the corners
#                    print("{")
#                    domain = grid[r][c][DOMAIN];
#                    crossed = grid[r][c][CROSSED];
#                    for (int i = 1; i <= RANGE; ++i) {
#                        if (domain & 1)
#                            printf("%d ", i);
#                        if (crossed & 1)
#                            printf("\\cancel{%d} ", i);
#                        domain >>= 1;
#                        crossed >>= 1;
#                        if(i % 2 == 0 && i != 8)
#                            printf("}{");
#                    }
#                    printf("}");
#                }
#                else
#                    printf("{}{}{}{}");
#                // Print actual value if one exists
#                if (grid[r][c][VALUE] > 0)
#                    printf("{%d}", grid[r][c][VALUE]);
#                else
#                    printf("{}");
#                // Ending(s)
#                if((c + 1) % 9 != 0)
#                    printf(" & ");
#                else
#                    printf(" \\\\ \\hline");
#                // Double line
#                if((c + 1) % 9 == 0 && (r + 1) % 3 == 0)
#                    printf("\\hline");
#              
#                if((c + 1) % 3 == 0)
#                    printf("\n");
        
        
    def latex_header(self):
        head = ("\\documentclass[10pt]{article}\n"
        "\\usepackage[left=0pt,right=0pt]{geometry}\n"
        "\\usepackage{tikz}\n"
        "\\usetikzlibrary{positioning}\n"
        "\\usepackage{cancel}\n"
        "\\pagestyle{empty}\n\n"
        "\\newcommand{\\N}[5]{\\tikz{\\node[label=above left:{\\tiny #1},\n"
        "                               label=above right:{\\tiny #2},\n" 
        "                               label=below left:{\\tiny #3},\n"
        "                               label=below right:{\\tiny #4}]{#5};}}\n\n"
        "\\begin{document}\n\n"
        "\\tikzset{every node/.style={minimum size=.5cm}}\n\n"
        "\\begin{center}\n"
        "\\begin{tabular}{||@{}c@{}|@{}c@{}|@{}c@{}||@{}c@{}|@{}c@{}|@{}c@{}||@{}c@{}|@{}c@{}|@{}c@{}||}\\hline\\hline\n");
        return head
        #print("%s" % (head))
    def latex_footer(self):
        foot = ("\\end{tabular}\n"
        "\\end{center}\n\n"
        "\\end{document}");
        return foot
        #print("%s" % (foot))
sudoku = Sudoku('/Users/rongdilin/Downloads/Assignment_2/sudoku_2.txt');
sudoku.preassess();
sudoku.bare_tex_output();
#print sudoku; 