import java.io.*;
import java.lang.*;
import java.util.StringTokenizer;
import DownloadURL;
import Download;

public class SharedFile
{
    boolean isFileChanged = false;


    Download download;

    public void setDownload(Download d)
    {
      this.download = d;
     
    }

    synchronized void construct(int depth,String scFormatFileName,String downloadTempLinksFileName)
    {
           RandomAccessFile scFormatFile = null;
           RandomAccessFile dTempLinksFile = null; 
           long scFormatFilePtr = 0,scFormatFileSize;
           long dTempLinksFilePtr = 0,dTempLinksFileSize;
           String link = null;
           byte linkRead = 0;
           try
           {
               scFormatFile = new RandomAccessFile(scFormatFileName,"rw");
               dTempLinksFile = new RandomAccessFile(downloadTempLinksFileName,"r");
    
               dTempLinksFile.seek(0);
               dTempLinksFileSize = dTempLinksFile.length();
    
               //do for all the links in the file
               while(dTempLinksFilePtr < dTempLinksFileSize)
               {
                   
                   link = new String(dTempLinksFile.readLine());
    
                  /**check if this particular link is the same
                   *if so check depth
                   */
            
                   scFormatFilePtr = 0;
                   scFormatFileSize = scFormatFile.length();
                   boolean linkNotFound = true;
                   StringTokenizer line;
                   scFormatFile.seek(0);
                   while((scFormatFilePtr < scFormatFileSize) && linkNotFound)
                   {

                     scFormatFile.readByte(); //initial byte
                     line = new StringTokenizer(scFormatFile.readLine());

                     if(line.nextToken().equals(link))
                     {
                         if(depth>(new Integer(line.nextToken())).intValue())
                         {
                            
                             //set the file to before the  link was
                             //extracted
                               scFormatFile.seek(scFormatFilePtr);
            
                               scFormatFile.write(linkRead);
                               scFormatFile.writeBytes(link);
                               scFormatFile.writeBytes("$");
                               scFormatFile.writeBytes(""+depth);
                               scFormatFile.writeBytes("$");
                               scFormatFile.writeBytes("0");//bytes completed
                               scFormatFile.writeBytes("$");
                               scFormatFile.writeBytes(extractName(link));//file 
          
                               scFormatFile.writeBytes("\r\n");
                           }
                           linkNotFound = false;
                       }
                       scFormatFilePtr = scFormatFile.getFilePointer();
                   }
                   if(linkNotFound)
                   {
                       scFormatFile.seek(scFormatFile.length());
    
                       scFormatFile.write(linkRead);
                       scFormatFile.writeBytes(link);
                       scFormatFile.writeBytes("$");
                       scFormatFile.writeBytes(""+depth);              //depth
                       scFormatFile.writeBytes("$");
                       scFormatFile.writeBytes("0");                   //bytes Completed
                       scFormatFile.writeBytes("$");
                       String fileName = extractName(link);
                       scFormatFile.writeBytes(fileName);                //file to write to
        
                       scFormatFile.writeBytes("\r\n");
                   }

        
                   dTempLinksFilePtr = dTempLinksFile.getFilePointer();
                     
               }//while
    
               dTempLinksFile.close();
               scFormatFile.close();

           }
           catch(FileNotFoundException fe)
           {
              System.out.println(fe);
         //     notify();
           }
           catch(IOException ie)
           {
              System.out.println(ie);
       //       notify();
              isFileChanged = true;
           }
           isFileChanged = true;
         //  notify();
    }

    String extractName(String url)
    {
        int i = 0;
        StringTokenizer link = new StringTokenizer(url,"/?;:*",false);
        String token = null;
        while(link.hasMoreTokens())
            token = link.nextToken();
        String fileName , extension;
        link = new StringTokenizer(token,".",false);
        fileName = link.nextToken();
        extension = "";
        while(link.hasMoreTokens())
        {
            if (!extension.equals(""))
                fileName = extension;
            extension = link.nextToken();
        }

        if (extension.equals("com"))
            extension = "html";

        File file = new File(fileName + "." + extension);

        while(file.exists())
        {
            i++;
            file = new File(fileName + i +"." + extension);
        }
        if (i == 0)
            return (download.directory+File.separator+ fileName + "." + extension);
        else
            return (download.directory+File.separator+ fileName + i + "." + extension);
    }

    synchronized void construct(String dUrlListFileName,String scFormatFileName,int depth)
    {
       long scFilePtr = 0, scFileSize;
       long uFilePtr = 0, uFileSize;
       String url,fileName;
       byte linkRead = 0;
       StringTokenizer line;
     /*
       try
       {
          wait();
       }
       catch(InterruptedException ie)
       {
          System.out.println(ie);
       }
     */
       try
       {
           System.out.println("atleast entering");
           RandomAccessFile scFormatFile = new RandomAccessFile(scFormatFileName,"rw");
           RandomAccessFile durlFile = new RandomAccessFile(dUrlListFileName,"rw");

            uFileSize = durlFile.length();
           /**check if this particular link is
             *already present
             *if so check depth
             */
           while(uFilePtr < uFileSize)
           {
               scFilePtr = 0;
               scFileSize = scFormatFile.length();
               scFormatFile.seek(0);
               
               boolean linkNotFound = true;
               
               url = durlFile.readLine();
               System.out.println(url);

               fileName = extractName(url);
               System.out.println(fileName);

               while((scFilePtr < scFileSize) && linkNotFound)
               {
                   scFormatFile.readByte();

                   line = new StringTokenizer(scFormatFile.readLine());

                   if(line.nextToken().equals(url))
                   {
                       
                       if(depth > (new Integer(line.nextToken())).intValue())
                       {
                        
                         //set the file to before the  link was
                         //extracted
                           scFormatFile.seek(scFilePtr);
                          
                           scFormatFile.write(linkRead);
                           scFormatFile.writeBytes(url);
                           scFormatFile.writeBytes("$");
                           scFormatFile.writeBytes(""+depth);        //depth
                           scFormatFile.writeBytes("$");
                           scFormatFile.writeBytes("0");             //bytes Completed
                           scFormatFile.writeBytes("$");
                           scFormatFile.writeBytes(fileName);        //file to write to
                           scFormatFile.writeBytes("\r\n");
                           
                       }
                       linkNotFound = false;
                   }
                   scFilePtr = scFormatFile.getFilePointer();
               }
               if(linkNotFound)
               {
                   scFormatFile.seek(scFormatFile.length());
    
                   scFormatFile.write(linkRead);
                   scFormatFile.writeBytes(url);
                   scFormatFile.writeBytes("$");
                   scFormatFile.writeBytes("" + depth);              //depth
                   scFormatFile.writeBytes("$");
                   scFormatFile.writeBytes("0");                     //bytes Completed
                   scFormatFile.writeBytes("$");
                   scFormatFile.writeBytes(fileName);                //file to write to
                   scFormatFile.writeBytes("\r\n");
               }
        
               uFilePtr = durlFile.getFilePointer();
           }
           durlFile.close();
           scFormatFile.close();

       }
       catch(FileNotFoundException fe)
       {
          System.out.println(fe);
         // notify();
       }
       catch(IOException ie)
       {
          System.out.println(ie);
          isFileChanged = true;
         // notify();
    
       }
      
       isFileChanged = true;
      // notify();
       System.out.println("coming till here....?");

    }

    synchronized void windUp(String scFormatFileName)
    {
         byte linkRead = 0;
         try
         {
             FileOutputStream f = new FileOutputStream(scFormatFileName);
             f.close();
             RandomAccessFile scFormatFile = new RandomAccessFile(scFormatFileName,"rw");
             for(int i = 0; i< download.MAX; i++)
             {
                  if(download.urlList[i].over == 0)
                  {
                      scFormatFile.write(linkRead);
                      scFormatFile.writeBytes(download.urlList[i].url);
                      scFormatFile.writeBytes("$");
                      scFormatFile.writeBytes(""+download.urlList[i].depth);
                      scFormatFile.writeBytes("$");
                      scFormatFile.writeBytes(""+download.urlList[i].bytesCompleted);
                      scFormatFile.writeBytes("$");
                      scFormatFile.writeBytes(download.urlList[i].fileName);
                      scFormatFile.writeBytes("\r\n");
                       
                  }
             }
             scFormatFile.close();
         }
         catch(IOException ie)
         {
         }
    }

    synchronized void construct(String url,String fileName,String scFormatFileName,int depth)
    {
      /*
       try
       {
          System.out.println("started waiting");
          wait();
          System.out.println("finished waiting");
       }
       catch(InterruptedException ie)
       {
          System.out.println(ie);
       }
     */
       try
       {
           RandomAccessFile scFormatFile = new RandomAccessFile(scFormatFileName,"rw");
           scFormatFile.seek(0);
    
           /**check if this particular link is
             *already present
             *if so check depth
             */
    
           long scFilePtr = 0,scFileSize = scFormatFile.length();
           boolean linkNotFound = true;
           StringTokenizer line;
           byte linkRead = 0;
    
           while((scFilePtr < scFileSize) && linkNotFound)
           {
               scFormatFile.readByte();
               line = new StringTokenizer(scFormatFile.readLine());
               if(line.nextToken().equals(url))
               {
                   
                   if(depth >(new Integer(line.nextToken())).intValue())
                   {
                    
                     //set the file to before the  link was
                     //extracted
                       scFormatFile.seek(scFilePtr);
                      
                       scFormatFile.write(linkRead);
                       scFormatFile.writeBytes(url);
                       scFormatFile.writeBytes("$");
                       scFormatFile.writeBytes(""+depth);        //depth
                       scFormatFile.writeBytes("$");
                       scFormatFile.writeBytes("0");             //bytes Completed
                       scFormatFile.writeBytes("$");
                       scFormatFile.writeBytes(fileName);        //file to write to
    
                       scFormatFile.writeBytes("\r\n");
    
                       linkNotFound = false;
                   }
               }
               scFilePtr = scFormatFile.getFilePointer();
           }
    
           if(linkNotFound)
           {
               scFormatFile.seek(scFormatFile.length());

               scFormatFile.write(linkRead);
               scFormatFile.writeBytes(url);
               scFormatFile.writeBytes("$");
               scFormatFile.writeBytes("" + depth);              //depth
               scFormatFile.writeBytes("$");
               scFormatFile.writeBytes("0");                     //bytes Completed
               scFormatFile.writeBytes("$");
               scFormatFile.writeBytes(fileName);                //file to write to

               scFormatFile.writeBytes("\r\n");
           }
           
       scFormatFile.close();
       }
       
       catch(FileNotFoundException fe)
       {
          System.out.println(fe);
       //   notify();
       }
       catch(IOException ie)
       {
          System.out.println(ie);
          isFileChanged = true;
        //  notify();
    
       }
       isFileChanged = true;
      // notify();
    

    }

    synchronized public void deleteAll(String scFormatFileName)
    {
        /*
        try
        {
           wait();
        }
        catch(InterruptedException ie)
        {
           System.out.println(ie);
        }
        */
        try
        {
          FileOutputStream f = new FileOutputStream(scFormatFileName);
          f.close();
        }
        catch(FileNotFoundException fe)
        {

        }
        catch(IOException fe)
        {

        }

//        File delFile = new File(scFormatFileName);
//        delFile.delete();
        //notify();
    }
    synchronized public void  readFile()
    {
        RandomAccessFile scFormatFile=null;
        File scFormatFileHandle=null;
        long scFilePtr = 0,scFileSize;
        byte linkRead = 1;
        int urlIndex = 0;
        /*
        try
        {
           wait();
        }
        catch(InterruptedException ie)
        {
           System.out.println(ie);
        }
        */
        try
        {
            scFormatFile = new RandomAccessFile(download.scFormatFileName,"rw");
            scFileSize = scFormatFile.length();
           
    
            while((scFilePtr < scFileSize) && (urlIndex < download.MAX))
            {
                while((download.urlList[urlIndex].over == 0) && urlIndex < download.MAX)
                       urlIndex++;
                if(urlIndex >= download.MAX)
                       break;

                if(scFormatFile.readByte() == 0)
                {
                   // download.noOfUrls++;
                    scFormatFile.seek(scFormatFile.getFilePointer()-1);
                    scFormatFile.write(linkRead);
                    StringTokenizer token = new StringTokenizer(scFormatFile.readLine(),"$",false);
                                        
    
                    String url = token.nextToken();
                    int depth = (new Integer(token.nextToken())).intValue();
                    long bytes = (new Integer(token.nextToken())).intValue();
                    String fileName = token.nextToken();

                    download.urlList[urlIndex].setData(url,depth,bytes,fileName,0);

//                    download.urlList[urlIndex].over = 0;

                    scFilePtr = scFormatFile.getFilePointer();
                }
            }
    
            scFormatFile.close();
            isFileChanged = false;
    //        notify();
        }
        catch(FileNotFoundException fe)
        {
        }
        catch(IOException ie)
        {
        }
    }


}


