Unit Config;

{$mode objfpc}{$H+}

Interface
Uses
  Classes, SysUtils, ShlepsUtils, dialogs;


Var ConfigFile:TStringList;
    ICommands:TStringList;

Procedure LoadConfigFile;
Procedure InitModule;
Function ExecCommand(Command:String):String;
Procedure LoadConfigPart(FName:String);

Implementation
Uses Dispatcher;

Procedure LoadConfigPart(FName:String);
Var Buf:TStringList;
    I,P:Longint;  b,pb:String;
Begin
  Buf:=TStringList.Create;
  Try
    Buf.LoadFromFile(OSPath(FName));
  Except
    LogMessage(0,'Can''t open configuration file:'+OSPath(FName));
  End;
  If Buf.Count>0 Then
    For I:=0 To Buf.Count-1 Do Begin
      b:=Buf[I];
      repeat
        P:=Pos(' ',b);      //remove useless space in the beginning of line
        If P=1 Then Begin
          Delete(b,1,1);
          P:=Pos(' ',b);
        End;
      Until (P<1)Or(P>1);
      If Pos(';',b)=1 Then Continue; // ; in the beginning is comment
      If Pos('#',b)=1 Then Continue; // # in the beginning is comment
      If Pos('//',b)=1 Then Continue; // // in the beginning is comment
      If Pos('include',LowerCase(b))=1 Then Begin
        pb:=Copy(b,9,Length(b)-8);
        LoadConfigPart(OSPath(pb));
        Continue;
      End;
      ConfigFile.Add(b);
    End;
    Buf.Free;
End;


Procedure LoadConfigFile;
Var Fname:String;
    I:Longint;
Begin
  FName:='';
  If ParamCount>0 Then
    For I:=1 To ParamCount Do
      If Pos('config=',LowerCase(ParamStr(I)))=1 Then Begin
        FName:=Copy(ParamStr(I),8,Length(ParamStr(I))-7);
        Break;
      End;
  If FName='' Then Begin
    Fname:=OSPath(ExtractFilePath(ParamStr(0))+ExtractFileName(ParamStr(0))+'.conf');
  End;
  ConfigFile:=TStringList.Create;
  LoadConfigPart(FName);
  Configfile.SaveToFile('configfile.effective');
End;

Procedure InitModule;
Begin
{  InterpreterForm.ModulesList.Items.Add('Config');
  ICommands:=TStringList.Create;
  ICommands.Add('Config::clear:');
  ICommands.Add('Config::load:<file>');}
End;

Function ExecCommand(Command:String):String;
var B,PB,Obj,Cmd,Attr:String;
Begin
  Obj:=GetNextToken(Command,PB,':');
  B:=PB;
  Cmd:=GetNextToken(B,PB,':');
  Attr:=PB;
  If Obj='' Then Begin
    If LowerCase(Cmd)='clear' Then ConfigFile.Clear;
    If LowerCase(Cmd)='load' Then 
       If Attr='' Then Begin
         LoadConfigFile;
         Result:='default config loaded';
       End
       Else Begin
         LoadConfigPart(Attr);
         Result:=Attr+' config loaded';
       End;

  End;
End;


Initialization
ICommands:=TStringList.Create;

End.

