 //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    = 'filmtv';
 SCRIPT_DESC    = '[IT] Get movie information from Film.tv.it';
 SCRIPT_LANG    = $09; //English
 SCRIPT_TYPE    = stMovies;
 
 BASE_URL    = 'http://www.film.tv.it';
 RATING_NAME = 'filmtv';
 
 SEARCH_STR  = 'http://www.film.tv.it/cerca.php?q=%s';

 
 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';
//riga150
//Global variables 
var
 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]; 
//riga 200
end;

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, URL : String;
begin
 curPos := Pos('Con <a href="', HTML);
if curPos < 1 then
  Exit;
 LogMessage('Parsing cast...'); 
  
 //Actors              
 curPos := curPos + 13;
 EndPos := PosFrom('"', HTML, curPos);
 while (curPos > 12) AND (curPos < Pos('menu-scheda"', HTML))  do begin
  URL := Trim(Copy(HTML, curPos, EndPos - curPos));
  curPos := EndPos + 2;
  EndPos := PosFrom('</a>', HTML, curPos);
  Name := Copy(HTML, curPos, EndPos - curPos);   
  curPos := EndPos;
  AddMoviePerson(Name, '', '', URL, ctActors);
  LogMessage('Actor:' + Name + ' ' + URL);
  curPos := PosFrom('<a href="', HTML, curPos)+9;
  EndPos :=PosFrom('"', HTML, curPos);
  if curPos > PosFrom('menu-scheda', HTML, EndPos) then
//riga 250
   Exit;
 end;
end;

procedure ParseReview(HTML : String);
var
 curPos, EndPos : Integer;
 strDescription, sommario, Trama, commento : String;
begin
 LogMessage('Parsing review...');  
 curPos := Pos('<p class="sommario">', HTML);
 if curPos > 1 then begin
  LogMessage('review 1 - Pos='+IntToStr(Pos('<p class="sommario">', HTML)));  
  //sommario          
  curPos := curPos +20;
  EndPos := PosFrom('</p>', HTML, curPos);
  sommario := Trim(Copy(HTML, curPos, EndPos - curPos));
 end else
 sommario := '';
 curPos := Pos('<p class="trama">', HTML);
 if curPos > 1 then begin
  EndPos := PosFrom('</p>', HTML, curPos);
  Trama := Trim(Copy(HTML, curPos+17, EndPos - curPos-17));
 end else
 Trama := '';
 curPos := Pos('<p class="commento">', HTML);
 if curPos > 1 then begin
  EndPos := PosFrom('</p>', HTML, curPos);
  commento := Trim(Copy(HTML, curPos+20, EndPos - curPos-20));
 end else
 commento := '';
 strDescription := Trim(HTMLToText(sommario + ' ' +Trama + ' '+commento));
 strDescription := StringReplace(strDescription, '<i>', '',true,false,false);
 strDescription := StringReplace(strDescription, '</i>', '',true,false,false);

 
 if Trim(strDescription) <> '' then begin
	 AddFieldValue(mfDescription, Trim(strDescription)); 
	 LogMessage('Recensione: '+  strDescription);  
 end;
end;


procedure ParseMovie(MovieURL : String; HTML : String);
var
 curPos, EndPos, limite : Integer;
 Name, URL, Title  : String;
begin
 LogMessage('Parsing movie...'); 
 // intParsed := 0;

 //Title 
//riga 300
 curPos := Pos('"scheda">', HTML);
 if curPos > 0 then begin
   curPos := PosFrom('<h1>', HTML, curPos)+4;
   EndPos := PosFrom('</h1>', HTML, curPos);
   Title := Trim(Copy(HTML, curPos, EndPos - curPos));
   AddFieldValue(mfOrigTitle, Title ); 
   LogMessage('Original Title:' + Title);
 end;
 //else
  // begin
  //   curPos := Pos('<h1>', HTML);
  //   curPos := curPos + Length('<h1>');
  //   EndPos := PosFrom('</h1>', HTML, curPos);
  //   AddFieldValue(mfOrigTitle, Trim(Copy(HTML, curPos, EndPos - curPos)) ); 
  //   LogMessage('Original Title:' + Trim(Copy(HTML, curPos, EndPos - curPos)));
  // end;
 
 //Country
 curPos := Pos('nazione=', HTML); 
 if curPos > 0 then begin
  curPos := PosFrom('>', HTML, curPos)+1; 
  EndPos := PosFrom('</a>', HTML, curPos); 
  AddFieldValue(mfCountry, Trim(Copy(HTML, curPos , Endpos - curPos ))); 
  LogMessage('Country: ' + Trim(Copy(HTML, curPos , Endpos - curPos )));
 end else

 //Anno
 curPos := PosFrom('cerca.php?anno=', HTML, curPos); 
 if curPos > 0 then begin
  curPos := PosFrom('">', HTML, curPos) + 2;
  EndPos := PosFrom('</', HTML, curPos);
  AddFieldValue(mfYear, Trim(Copy(HTML, curPos , Endpos - curPos ))); 
  LogMessage('Anno: ' + Trim(Copy(HTML, curPos , Endpos - curPos )));
 end else
 
 //Genere
 curPos := Pos('genere=', HTML);
 if curPos > 0 then begin
  curPos := PosFrom('">', HTML, curPos) + 2;
  EndPos := PosFrom('</', HTML, curPos);
  AddFieldValue(mfGenre, Copy(HTML, curPos, EndPos - curPos) ); 
  LogMessage('Genere:' + Copy(HTML, curPos, EndPos - curPos) );  
 end;

 //Duration 
 curPos := Pos('>, durata', HTML);
 if curPos > 0 then begin
  curPos := curPos + 10;
  EndPos := curPos +2;
//riga 350
  LogMessage('Durata1: Pos=' + IntToStr(curPos) + ' EndPos='+ IntToStr(Endpos)+ ' min.='+ Trim(Copy(HTML, curPos, EndPos - curPos)));
  //se minuti < 20 allora endpos = curpos +12
   if StrToInt(Trim(Copy(HTML, curPos, EndPos - curPos)))<20 then

    EndPos := EndPos+1;
    LogMessage('Durata2: Pos=' + IntToStr(curPos) + ' EndPos='+ IntToStr(Endpos)+ ' min.='+ Trim(Copy(HTML, curPos, EndPos - curPos)));
  AddFieldValue(mfDuration, Trim(Copy(HTML, curPos, EndPos - curPos))); 
  LogMessage('Durata:' + Trim(Copy(HTML, curPos, EndPos - curPos)));
 end;

 //Director
 curPos := Pos('Regia di <a href=', HTML);
 if Pos('con <', HTML) > 0 then
  limite := Pos('con <', HTML)
 else
 limite := PosFrom('-scheda', HTML, curPos);
 if curPos > 0 then begin
  curPos := curPos +18;
  while (curPos > 17) AND (curPos < limite) do begin
   EndPos := PosFrom('">', HTML, curPos);
   URL := BASE_URL + Trim(Copy(HTML, curPos, EndPos - curPos));

   curPos := EndPos + 2;
   EndPos := PosFrom('</a>', HTML, curPos);
   Name := Trim(Copy(HTML, curPos, EndPos - curPos)); 
   AddMoviePerson(Name, '', '', URL, ctDirectors);
   LogMessage('Director: ' + Name + ', Url: ' + URL);
   curPos := PosFrom('<a href="', HTML, curPos)+9;
  end;
 end;


 //Get URL
 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);

 //Poster
 curPos := Pos('http://www.film.tv.it/imgbank/LOC/', HTML);
 if curPos > 0 then begin
  EndPos := PosFrom('"', HTML, curPos);
  ExtraLinks[smPoster] := StringReplace(Copy(HTML, curPos, EndPos - curPos), '/LOC/', '/GALLERY/',true,false,false);
  LogMessage('Poster:' + ExtraLinks[smPoster] );
 end;
//riga 400
 //Rating
 
 curPos := Pos('Il voto di', HTML);
 curPos := PosFrom('rating', HTML, curPos);
 if curPos > 0 then begin
  curPos := curPos + 7;
 EndPos := PosFrom('.gif', HTML, curPos);
  AddFieldValue(mfRating, FloatToStr(StrToFloat(Copy(HTML, curPos, EndPos - curPos)) * 2));  
  LogMessage('Rating:' + FloatToStr(StrToFloat(Copy(HTML, curPos, EndPos - curPos)) * 2));
 end else 
  curPos := EndPos;
end;


//riga450
 
 

procedure ParseSearchResults(HTML : String);
var
 intInitPos, curPos, EndPos : Integer;
 Title, Titole2, Year, URL : String;
begin
 curPos := Pos('d">ricerca avanzata', HTML);
 if curPos < 1 then
 //riga500
  Exit;
  
 LogMessage('Parsing search results...');  

 intInitPos := curPos;
 curPos := PosFrom('<a href="/film/', HTML, curPos); 
 while curPos > 0 do begin
  EndPos := PosFrom('">', HTML, curPos);
  URL := Copy(HTML, curPos + 9, EndPos - curPos - 9);
  LogMessage('curPos= '+IntToStr(CurPos)+' EndPos= '+IntToStr(EndPos)); 
  URL := BASE_URL + URL;
  LogMessage('Url= '+URL); 
  curPos := PosFrom('title="', HTML, curPos)+7;  
  EndPos := PosFrom('">', HTML, curPos);
  Title := Copy(HTML, curPos, EndPos - curPos);
  Title := StringReplace(Title, '<em>' , '',true,false,false)
  Title := StringReplace(Title, '</em>', '',true,false,false)
  Title := StringReplace(Title, '<b>', '',true,false,false)  
  Title := StringReplace(Title, '</b>', '',true,false,false)  
  
  if Length(Title) > 80 then Title := Copy(Title, 1, 80);
  LogMessage('curPos= '+IntToStr(CurPos)+' EndPos= '+IntToStr(EndPos)+' Title= '+Title); 
  
  curPos := PosFrom('span>', HTML, curPos)+5;
  EndPos := PosFrom('</span', HTML, curPos);
  
  Titole2 := Copy(HTML, curPos, EndPos - curPos);
//  LogMessage('curPos= '+IntToStr(CurPos)+' EndPos= '+IntToStr(EndPos)+' Title2= '+Title2); 
 
  Year := '';
  
  AddSearchResult(Title +' '+Titole2,'', Year, URL, '');
  LogMessage('Title= '+Title+'Titole2= '+Titole2+' Url='+URL); 

  curPos := PosFrom('opinioni', HTML, curPos); 
  curPos := PosFrom('<a href="/film/', HTML, curPos); 
 end;
end;

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

 for I := curMode + 1 to High(ExtraLinks) do
//riga550
  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.Sono stati Trovati=' + IntToStr(Pos('Sono stati trovati', HTML)));

 if Pos('Sono stati trovati', HTML) > 0 then begin
  ParseSearchResults(HTML);
  Result := prList; 
  Exit;
 end else
 LogMessage('ParsePage2: Pos."scheda"> =' + IntToStr(Pos('"scheda">', HTML)));
 if Pos('"scheda">',HTML) > 0 then begin
       //if intParsed = 0 then begin
  LogMessage('Inizio ParseCast');
  ParseCast(HTML);
  LogMessage('Inizio ParseReview');
  ParseReview(HTML);
  LogMessage('Inizio ParseMovie');
  ParseMovie(URL, HTML);
        // intParsed := 1;
 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.
