 //This version of script is for use with PVD versions 0.9.9.5 and above!!!
 //derived from allmovie template
(*
 Additional types and functions that can be used in scripts:

  //Types
  TWIDEARRAY : array of String

  //Field functions
  procedure AddSearchResult(Title1, Title2, Year, URL, PreviewURL : String)
  procedure AddFieldValue(AField: Integer; AValue : String)
  procedure AddMoviePerson(Name, TransName, Role, URL : String; AType : Byte)
  procedure AddPersonMovie(Title, OrigTitle, Role, Year, URL : String; AType : Byte)
  procedure AddAward(Event, Award, Category, Recipient, Year: String; const Won : Boolean)
  procedure AddConnection(Title, OrigTitle, Category, URL, Year: String)
  procedure AddEpisode(Title, OrigTitle, Description, URL, Year, Season, Episode : String)
  
  //String functions
  function Pos(Substr : String; Str: String): Integer
  function PosFrom(const SubStr, Str : String; FromIndex : Integer) : Integer
  function LastPos(const SubStr, Str : String) : Integer
  function PrevPos(const SubStr, Str : String; APos : Integer) : Integer
  function RemoveTags(AText : String; doLineBreaks : Boolean) : String
  function ExplodeString(AText : String; var Items : TWideArray; Delimiters : String) : Integer
  function Copy(S: String; Index, Count: Integer): String
  procedure Delete(var S: String; Index, Count: Integer)
  procedure Insert(Source: String; var Dest: String; Index: Integer)
  function Length(S: String): Integer
  function Trim(S: String): String
  function CompareText(S1, S2: String): Integer
  function CompareStr(S1, S2: String): Integer
  function UpperCase(S: String): String
  function LowerCase(S: String): String
  function StringReplace(S, OldPattern, NewPattern: String; ReplaceAll : Boolean; IgnoreCase : Boolean; WholeWord: Boolean): String
  function StrToInt(const S: String): Integer
  function IntToStr(const Value: Integer): String
  function StrToFloat(const S: String): Extended
  function FloatToStr(const Value: Extended): String

  function HTMLValues(const HTML : String; ABegin, AEnd, ItemBegin, ItemEnd : String; ValDelim : String; var Pos : Integer) : String
  function HTMLValues2(const HTML : String; ABegin, AEnd, ItemBegin, ItemEnd : String; ValDelim : String; var Pos :Integer) : String
  function TextBetween(const HTML : String; ABegin, AEnd : String; doLineBreaks : Boolean; var Pos : Integer) : String
  function HTMLToText(const HTML : String) : String

  procedure ShowMessage(const Msg, Head : String)
*)

//Some useful constants
const
//riga50
 //Script types
 stMovies = 0;
 stPeople = 1; 
 stPoster = 2;
  
 //Script modes
 smSearch     = 0; 
 smNormal     = 1;
 //smCast       = 2;
 //smReview     = 3;
 //smCredits    = 4;
 smAward      = 2;
 smPrePoster  = 3;
 smPoster     = 4;
 smFinished   = 5;
 
 //Parse results
 prError     = 0; 
 prFinished  = 1;
 prList      = 2;
 prListImage = 3;
 prDownload  = 4;
 
 //Download methods
 dmGET  = 0;
 dmPOST = 1;
 
 //Prefix modes
 pmNone   = 0;
 pmEnd    = 1;
 pmBegin  = 2;
 pmRemove = 3; 
  
 //Movie fields
 mfURL         = 0;
 mfTitle       = 1;
 mfOrigTitle   = 2;
 mfAka         = 3;
 mfYear        = 4;
 mfGenre       = 5;
 mfCategory    = 6;
 mfCountry     = 7;
 mfStudio      = 8;
 mfMPAA        = 9;
 mfRating      = 10;
 mfTags        = 11;
 mfTagline     = 12;
 mfDescription = 13;
 mfDuration    = 14;
//riga100
 mfFeatures    = 15;
  
 //People fields
 pfURL        = 0;
 pfName       = 1;
 pfTransName  = 2;
 pfAltNames   = 3;
 pfBirthday   = 4;
 pfBirthplace = 5;
 pfGenre      = 6;
 pfBio        = 7;
 pfDeathDate  = 8;
  
 //Credits types
 ctActors    = 0;
 ctDirectors = 1;
 ctWriters   = 2;
 ctComposers = 3;
 ctProducers = 4;
  
 //Script data 
 SCRIPT_VERSION = '0.1.0.6'; 
 SCRIPT_NAME    = 'ilcinematografo';
 SCRIPT_DESC    = '[IT] Get movie information from ilcinematografo';
 SCRIPT_LANG    = $09; //English
 SCRIPT_TYPE    = stMovies;
 
 BASE_URL    = 'http://ilcinematografo.forumcommunity.net/';
 RATING_NAME = 'ilcinematografo';
 SEARCH_STR  = 'http://www.google.it/custom?hl=it&q=%s+site%3Ailcinematografo.forumcommunity.net%2F&meta=';

 CODE_PAGE   = 65001; //Use 0 for Autodetect 

 //OPTIONS
 GET_THEMES  = True; //Set to False if you do not want Themes in Category field 
 GET_REVIEW  = True; 
 GET_CREDITS = True;
 
 //Custom field names to use
 IMPORTANCE_FIELD     = 'High Historical Importance'; 
 ARTQUALITY_FIELD     = 'High Artistic Quality';
 CREDITS_FIELD        = 'Production Credits'; 
 REVIEW_FIELD         = 'Review';
 HIGHBUDGET_FIELD     = 'High Budget';
 HIGHPRODUCTION_FIELD = 'High Production Value';
 CULT_FIELD           = 'Cult Film';

//Global variables 
var
//riga150
 ELI : Integer;
 //intParsed : Integer;
 Mode : Byte;
 ExtraLinks : array [smAward..smPoster] of String;
 
//Functions 
function GetScriptVersion : String;
begin
 Result := SCRIPT_VERSION;
end; 
 
function GetScriptName : String;
begin
 Result :=  SCRIPT_NAME;
end;

function GetScriptDesc : String;
begin
 Result := SCRIPT_DESC;
end;

function GetRatingName : String;
begin
 Result := RATING_NAME;
end;

function GetScriptLang: Cardinal;
begin
 Result := SCRIPT_LANG;
end;

function GetCodePage : Cardinal;
begin
 Result := CODE_PAGE;
end;

function GetBaseURL : AnsiString;
begin
 Result := BASE_URL;
end;

function GetDownloadURL : AnsiString;
begin
 if (Mode = smSearch) then
  Result := SEARCH_STR
 else
  Result := ExtraLinks[Mode]; 
end;

//riga 200
function GetDownloadMethod : Byte;
begin
 //if Mode = smSearch then
  // Result := dmPOST
 //else
  Result := dmGET;  
end;

function GetPrefixMode : Byte;
begin
 Result := pmBegin;  
end;

function GetScriptType : Byte; 
begin
 Result := SCRIPT_TYPE;
end;

function GetCurrentMode : Byte; 
begin
 Result := Mode;
end;

procedure ParseCast(HTML : String);
var
 curPos, EndPos : Integer;
 Name : String;
begin
 curPos := Pos('Interpreti', HTML);
 if curPos < 1 then
  Exit;
 LogMessage('Parsing cast...'); 
 //Actors              
 curPos := curPos +12;
 LogMessage('Actor1: Pos='+IntToStr(CurPos)+' EndPos= '+IntToStr(EndPos));

 while (curPos > 0) AND (curPos < Pos('Durata:', HTML)-4)  do begin
  EndPos := PosFrom(',', HTML, curPos);
  LogMessage('Actor2: Pos='+IntToStr(CurPos)+' EndPos= '+IntToStr(EndPos));

  if EndPos > PosFrom('Durata', HTML, curPos) then 
   EndPos := PrevPos('Durata', HTML, EndPos)-4;
   LogMessage('Actor3: Pos='+IntToStr(CurPos)+' EndPos= '+IntToStr(EndPos));
   Name := Trim(Copy(HTML, curPos, EndPos - curPos));
   AddMoviePerson(Name, '', '', '', ctActors);
   LogMessage('Actor:' + Name+' Pos= '+IntToStr(CurPos)+' EndPos= '+IntToStr(EndPos));
   curPos := EndPos+2;
  if curPos > PosFrom('Durata', HTML, EndPos)-4 then
   Exit;
 end;
end;


procedure ParseReview(HTML : String);
var
 curPos, EndPos : Integer;
//riga250
 strDescription : String;
begin
 LogMessage('Parsing review...');  
 curPos := Pos('Genere:', HTML);
 if curPos >1 then begin
  
  LogMessage('review 1: Pos='+IntToStr(curPos));  
  curPos := PosFrom('<i>', HTML, curPos)+3;
  EndPos := PosFrom('</p>', HTML, curPos);
  LogMessage('review 2: Pos='+IntToStr(curPos) + ' End='+IntToStr(EndPos));  
  if curPos <5 then
   exit;
  strDescription := Trim(HTMLToText(Copy(HTML, curPos, EndPos - curPos)));
  strDescription := StringReplace(strDescription, '<i>', '', true, false, false);
  strDescription := StringReplace(strDescription, '</i>','', true, false, false);
  strDescription := StringReplace(strDescription, '<br>', '', true, false, false);
  if Trim(strDescription) <> '' then begin
 	 AddFieldValue(mfDescription, Trim(strDescription)); 
 	 LogMessage('Recensione: '+  strDescription);  
  end;
 end;
end;

procedure ParseMovie(MovieURL : String; HTML : String);
var
 curPos, EndPos, ora, min, durata : Integer;
 Name, URL, Title  : String;
begin
 LogMessage('Parsing movie...'); 

 //Poster
 curPos := Pos('Titolo originale', HTML);
 LogMessage('movie-poster1: Pos='+IntToStr(curPos) + ' End='+IntToStr(EndPos));  
 curpos := PrevPos('src=', HTML, curPos);
 LogMessage('movie-poster2: Pos='+IntToStr(curPos) + ' End='+IntToStr(EndPos));  
 if curPos > 0 then begin
  EndPos := PosFrom('" alt=', HTML, curPos);
  LogMessage('movie-poster3: Pos='+IntToStr(curPos) + ' End='+IntToStr(EndPos));  
  ExtraLinks[smPoster] := Trim(Copy(HTML, curPos+5, EndPos - curPos-5));
  LogMessage('Poster:' + ExtraLinks[smPoster] );
 end;
 
 //Title 
 curPos := Pos('Titolo originale', HTML);
 LogMessage('movie-title1: Pos='+IntToStr(curPos) + ' End='+IntToStr(EndPos));  
 if curPos > 0 then begin   
   EndPos := PosFrom('Regia:', HTML, curPos);
   LogMessage('movie-title2: Pos='+IntToStr(curPos) + ' End='+IntToStr(EndPos));  
   Title := Trim(Copy(HTML, curPos+18, EndPos - curPos-18));
   AddFieldValue(mfOrigTitle, Title ); 
   LogMessage('Original Title:' + Title);
 end;

 //Director
 curPos := Pos('Regia:', HTML);
 LogMessage('movie-director1: Pos='+IntToStr(curPos) + ' End='+IntToStr(EndPos));  
 if curPos > 0 then begin
  curPos := curPos +7;
  EndPos := PosFrom('Interpreti', HTML, curPos);
  LogMessage('movie-director2: Pos='+IntToStr(curPos) + ' End='+IntToStr(EndPos));  
//riga 300
  Name := Trim(Copy(HTML, curPos, EndPos - curPos)); 
  URL := ''; 
  AddMoviePerson(Name, '', '', URL, ctDirectors);
  LogMessage('Director: ' + Name);
 end;

 //Cast

 //Duration 
 curPos := Pos('Durata:', HTML);
 if curPos > 0 then begin
  curPos := curPos + 10;
  EndPos := curPos +4;
  LogMessage('Durata1: Pos=' + IntToStr(curPos) + ' EndPos='+ IntToStr(Endpos)+ ' ore,min.='+ Trim(Copy(HTML, curPos, EndPos - curPos)));
  //EndPos := EndPos+1;
  // LogMessage('Durata2: Pos=' + IntToStr(curPos) + ' EndPos='+ IntToStr(Endpos)+ ' ore,min.='+ Trim(Copy(HTML, curPos, EndPos - curPos)));
  AddFieldValue(mfDuration, Trim(Copy(HTML, curPos, EndPos - curPos))); 
  LogMessage('Durata2:' + Trim(Copy(HTML, curPos, EndPos - curPos)));
  //se minuti < 5
  if StrToInt(Trim(Copy(HTML, curPos, EndPos - curPos)))<5 then begin
   EndPos := curPos + 1;
   ora := StrToInt(Trim(Copy(HTML, curPos, EndPos - curPos)));
   curPos := EndPos +1;
   EndPos := curPos +2;
   min := StrToInt(Trim(Copy(HTML, curPos, EndPos - curPos)));
   durata := ora * 60 + min;
   AddFieldValue(mfDuration, InttoStr(durata)); 
   LogMessage('Durata3:' + IntToStr(durata));
  end; 
 end;

 //Country
 curPos := Pos('Nazionalità:', HTML); 
 LogMessage('movie-country1: Pos='+IntToStr(curPos) + ' End='+IntToStr(EndPos));  
 if curPos > 0 then begin
  EndPos := PosFrom('Genere:', HTML, curPos)-5; 
  AddFieldValue(mfCountry, Trim(Copy(HTML, curPos+13, Endpos - curPos-13))); 
  LogMessage('movie-country2: Pos='+IntToStr(curPos+13) + ' End='+IntToStr(EndPos));  
  LogMessage('Country: ' + Trim(Copy(HTML, curPos+13 , Endpos - curPos-13 )));
 end;

 //Anno

 curPos := EndPos;
 LogMessage('movie-anno1: Pos='+IntToStr(curPos) + ' End='+IntToStr(EndPos));  
 if curPos > 0 then begin
  EndPos := curPos+4;
  AddFieldValue(mfYear, Trim(Copy(HTML, curPos , Endpos - curPos ))); 
  LogMessage('Anno: ' + Trim(Copy(HTML, curPos , Endpos - curPos )));
 end;
 
 //Genere
 curPos := Pos('Genere:', HTML);
 if curPos > 0 then begin
  EndPos := PosFrom('<', HTML, curPos);
  AddFieldValue(mfGenre, Copy(HTML, curPos+8, EndPos - curPos-8) ); 
  LogMessage('Genere:' + Copy(HTML, curPos+8, EndPos - curPos-8) );  
 end;

 //Get URL
 // AddFieldValue(mfURL, MovieURL);

//riga350
// curPos := Pos('l"><a href="/film', HTML);
// LogMessage('Url1: curpos='+ IntToStr(curPos)+' endpos='+IntToStr(EndPos));
// if curPos > 0 then begin
//  curPos := curPos + 12;
//  EndPos := PosFrom('"', HTML, curPos);
//  LogMessage('Url2: curpos='+ IntToStr(curPos)+' endpos='+IntToStr(EndPos)+' Url=' +Copy(HTML, curPos, EndPos - curPos));
//  AddFieldValue(mfURL, BASE_URL+Trim(Copy(HTML, curPos, EndPos - curPos)));
// end else
//  AddFieldValue(mfURL, MovieURL);
//  LogMessage('Url3: curpos='+ IntToStr(curPos)+' endpos='+IntToStr(EndPos)+' Url='+ MovieURL);

end;

procedure ParseSearchResults(HTML : String);
var
 intInitPos, curPos, EndPos : Integer;
 Title, Year, URL : String;
begin
 curPos := Pos('Cerca con', HTML);
 if curPos < 1 then
 Exit;
  
 LogMessage('Parsing search results...');  

 intInitPos := curPos;
 curPos := PosFrom('this,', HTML, curPos); 
 while curPos > 0 do begin
  EndPos := PosFrom(')', HTML, curPos)-1;
  URL := Copy(HTML, curPos + 7, EndPos - curPos - 7);
  LogMessage('curPos= '+IntToStr(CurPos)+' EndPos= '+IntToStr(EndPos)); 
  LogMessage('Url= '+URL); 
  curPos := PosFrom('">', HTML, curPos)+2;  
  EndPos := PosFrom('</', HTML, curPos);
  Title := StringReplace(Copy(HTML, curPos, EndPos - curPos), '<b>', '',true,false,false);

  if Length(Title) > 80 then Title := Copy(Title, 1, 80);
  LogMessage('curPos= '+IntToStr(CurPos)+' EndPos= '+IntToStr(EndPos)+' Title= '+Title); 
 
  Year := '';
  
  AddSearchResult(Title, '', Year, URL, '');
  LogMessage('Title= '+Title+' Url='+URL); 

  curPos := PosFrom('this,', HTML, curPos); 
 end;
end;

function NextMode(curMode : Integer) : Integer;
var
//riga400
 I : Integer;
begin
 Result := smFinished;
 if curMode < Low(ExtraLinks) - 1 then
  curMode := Low(ExtraLinks) - 1;

 for I := curMode + 1 to High(ExtraLinks) do
  if ExtraLinks[I] <> '' then begin
   LogMessage('Extralinks:' + IntToStr(I) );
   Result := I;
   Break;
  end;
end;

function ParsePage(HTML : String; URL : AnsiString) : Cardinal;
begin
 HTML := HTMLToText(HTML);
 LogMessage('ParsePage1: Pos.Cerca con=' + IntToStr(Pos('Cerca con', HTML)));

 if Pos('Cerca con', HTML) > 0 then begin
  ParseSearchResults(HTML);
  Result := prList; 
  Exit;
 end else
 LogMessage('ParsePage2: Pos.Titolo originale' + IntToStr(Pos('Titolo originale', HTML)));
 if Pos('Titolo originale',HTML) > 0 then begin
  LogMessage('Inizio ParseCast');
  ParseCast(HTML);
  LogMessage('Inizio ParseReview');
  ParseReview(HTML);
  LogMessage('Inizio ParseMovie');
  ParseMovie(URL, HTML);
 end;

 Mode := NextMode(Mode);
 if Mode <> smFinished then
  Result := prDownload
 else
  Result := prFinished;  
end;

begin
 Mode := smSearch;

 for ELI := Low(ExtraLinks) to High(ExtraLinks) do
  ExtraLinks[ELI] := '';
end.
