package hy222ap_assign1;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class SubtitutionDecryption {
	
		
	    
		private String text="";
		private String newtext="";
		private static ArrayList<String>keys=new ArrayList<String>();
		private Key[] secret=null;
		
		
		
		
		private static String readFile(String path) throws IOException{
			
			StringBuilder text=new StringBuilder();
			
			Scanner scan=new Scanner(new File(path));
			
			while(scan.hasNext())
				text.append(scan.nextLine()+"\n");
			
			scan.close();
			return text.toString();
			
			
		}
		
	    
		
		public SubtitutionDecryption(){
			
			
		}
		
		public void Input(){
			
			try{
				text = readFile("/Users/CaptainYan/Desktop/SubtitutionEncryption.txt");
				
				
			}catch(IOException e){
				
				e.printStackTrace();
				
			}
			
		}
		
		public void InputKey(){
			

			String key="";
			
			try{
				key = readFile("/Users/CaptainYan/Desktop/SubtitutionKey.txt");  //file format like a-A
				
				
			}catch(IOException e){
				
				e.printStackTrace();
				
			}
			
			 Scanner scan=new Scanner(key);
				
				while(scan.hasNext())
				{
					
					keys.add(scan.nextLine());
					
					
				}
				
				scan.close();
				
				Key[] ky=new Key[keys.size()];
				
				for(int i=0;i<keys.size();i++)
				{
					ky[i]=new Key(keys.get(i));
					
				}
				
				secret=ky;
				
				
				
			
			
			
		}
		
		public void Output() throws IOException{
			
			File outFile = new File("/Users/CaptainYan/Desktop/SubtitutionDecryption.txt");
			PrintWriter printer= new PrintWriter(outFile);
			printer.print(newtext);
			printer.close();
			
			
			
			
		}
		
		public void Decrypt(){
			
			
			String tmp="";
			tmp=text;
			
			
			for(int i=0;i<tmp.length();i++)                               //decrypt substitution
			{
				for(int j=0;j<secret.length;j++)
				{
					if(tmp.charAt(i)==secret[j].getnewword().charAt(0))
					{
						
						tmp=tmp.replace(tmp.charAt(i), secret[j].getorginalword().charAt(0));
						
						
					}
					
				}
				
			}
			
			
			newtext=tmp;
			
			
			
			
			
		}
		
		
		
		
		
		

	}

	
	


