unit AcExport;

interface

uses
  AcStruc, mteTypes;

procedure ExportDescToFile(Iface: TMicexIface; const FileName, Url: string);

implementation

uses
  HtmlOut, SysUtils, TypInfo, Graphics, Classes;

const
  TableColor  = $F0F0F0;
  HeaderColor = clLtGray;

  STableFlags: array [Boolean, Boolean] of string =
    (('(не обновляемая)', '(ошибка)'),
     ('(обновляемая)', '(обновляемая, очищать при обновлении)'));
  SNoFields: array [Boolean] of string = ('Входн', 'Выходн');
  SFieldTypes: array [TTEFieldType] of string =
    ('CHAR', 'INTEGER', 'FIXED', 'PRICE', 'DATE', 'TIME', 'FLOAT');
  SBools: array [Boolean] of string = (NbSp, 'X');

function ToCell(const Msg: string): string;
begin
  if Trim(Msg) = '' then Result := NbSp else Result := Msg;
end;

procedure ExportDesc(Msg: TMicexMessage; Html: THtmlWriter);
begin
{  if Assigned(Msg) and (Msg.FDescr <> '') then
  begin
    Html.Write(Msg.FDescr);
    Html.Paragraph;
  end;}
end;

procedure SaveFields(Fields: TMicexFields; IsOutput: Boolean;
  Html: THtmlWriter; HasDescriptions: Boolean);

  function CheckKey(const S: string; IsKey: Boolean): string;
  begin
    if IsKey then Result := '<b>' + S{ + '</b>' }else Result := S;
  end;

var
  I: Integer;
  S, FldDesc: string;
begin
  FldDesc := '';
  with Html do
  begin
    if Fields.Count = 0 then
    begin
      Write(SNoFields[IsOutput] + 'ых полей нет');
      NewLine;
    end
    else
    begin
      Table(1, 1, 0, 90);
        TableRow(HeaderColor);
          TableColW(SNoFields[IsOutput] + 'ое поле', 15);
          TableColW('Наименование', 20);
          TableColW('Тип', 7);
          TableColW('Размер', 5, taRightJustify);
//          TableCol('Ключ', taCenter);
//          TableCol('Код бумаги', taCenter);
//          if not IsOutput then TableCol('По умолчанию');
          if HasDescriptions then TableCol('Примечание');
        EndTag;

        for I := 0 to Fields.Count - 1 do
          with TMicexField(Fields[I]) do
        begin
          TableRow(TableColor);
            //S := Name;
(*            if FDescr <> '' then
            begin
              S := Format('<a href="#f%d">', [FldDescRef]) + S + '</a>';

{              FldDesc := FldDesc + Format('<p><a name="f%d">',
                [FldDescRef]) + '<i>' + FName + ': </i>' + FDescr + CrLf;}
              FldDesc := FldDesc + Format('<tr><td width=15%%><p><a name="f%d">',
                [FldDescRef]) + FName + '</td><td>' + FDescr + '</td></tr>' + CrLf;

              Inc(FldDescRef);
            end;*)

            S := '<td bgcolor="#e0e0e0">';
            if Key then S := S + '<b>';
            S := S + Name;
            if SecCode then S := S + '<a href=#refs>*</a>';
            if VarBlock then S := S + '<a href=#refs>+</a>';
            Writeln(S + '</td>');

            TableCol(CheckKey(ToCell(Caption), Key));

            if Assigned(EnumPtr) then
            begin
              Tag(htColumn);
              S := EnumPtr.Name;
              HRef(CheckKey(S, Key), '#e' + S);
              EndTag;
            end
            else begin
              S := SFieldTypes[FieldType];
              TableCol(CheckKey(S, Key));
            end;

            TableCol(CheckKey(GetDecimalsStr, Key), taRightJustify);
//            TableCol(SBools[Key], taCenter);
//            TableCol(SBools[SecCode], taCenter);

//            if not IsOutput then TableCol(ToCell(DefValue));
            if HasDescriptions then TableCol(CheckKey(ToCell(Description), Key));
          EndTag;
        end;
      EndTag;

      if FldDesc <> '' then
      begin
        Paragraph;
        Table(1, 1, 0, 90);
          Write(FldDesc);
        EndTag;
      end;
    end;
  end;
end;

procedure ExportIface(Iface: TMicexIface; Html: THtmlWriter);

  function GetSystemIndex(const SystemIndex: Integer): string;
  begin
    if SystemIndex <> 0 then
      Result := Format(', SystemIndex=%d', [SystemIndex])
    else
      Result := '';
  end;

var
  I: Integer;
  Upd, Clr: Boolean;
begin
  with Html do
  begin
    Separator;
{    Bookmark('i');
    TaggedText(Format('Интерфейс %s - %s', [Iface.FName, Iface.FCaption]), [htH2]);
    Separator;}
    Bookmark('it');
    TaggedText('Таблицы', [htH3]);
    Indent;

    for I := 0 to Iface.Tables.Count - 1 do
      with Iface.Tables[I] do
    begin
      Upd := Updateable;
      Clr := ClearOnUpdate;
      Bookmark('t' + IntToStr(I));
      TaggedText(Format('%s - %s %s%s',
        [Name, Caption, STableFlags[Upd, Clr], GetSystemIndex(SystemIndex)]), [htH4]);

      Indent;
      if Description <> '' then
      begin
        Html.Write(Description);
        Html.Paragraph;
      end;

      SaveFields(InFields, False, Html, Iface.HasDescriptions);
      if InFields.Count > 0 then Paragraph;
      SaveFields(OutFields, True, Html, Iface.HasDescriptions);
      Unindent;
    end;

    Unindent;
    Separator;
    Bookmark('ir');
    TaggedText('Транзакции', [htH3]);
    Indent;
    for I := 0 to Iface.Transactions.Count - 1 do
      with Iface.Transactions[I] do
    begin
      Bookmark('r' + IntToStr(I));
      TaggedText(Format('%s - %s%s', [Name, Caption, GetSystemIndex(SystemIndex)]), [htH4]);

      Indent;
      if Description <> '' then
      begin
        Html.Write(Description);
        Html.Paragraph;
      end;

      SaveFields(InFields, False, Html, Iface.HasDescriptions);
      Unindent;
    end;
    Unindent;
  end;
end;

procedure ExportEnums(Iface: TMicexIface; Html: THtmlWriter);
var
  I, Idx: Integer;
begin
  with Html do
  begin
    Bookmark('e');
    TaggedText('Перечислимые типы', [htH3]);
    Indent;

    for I := 0 to Iface.Types.Count - 1 do
      with Iface.Types[I] do
    begin
      Bookmark('e' + Name);
      TaggedText(Format('%s - %s (длина: %d, тип: %s)',
        [Name, Caption, Size,
          GetEnumName(TypeInfo(TTEEnumKind), Integer(Kind))]), [htH4]);

      Indent;
      if Description <> '' then
      begin
        Write(Description);
        Paragraph;
      end;

      Table(1, 1, 0, 50);
        TableRow(HeaderColor);
          Write('<td width=20%>Константа</td>' + CrLf);
          if Iface.HasDescriptions then
            Write('<td width=20%>' + 'Краткое обозначение' + '</td>' + CrLf);
          TableCol('Описание');
        EndTag;

        for Idx := 0 to GetConstCount - 1 do
        begin
          TableRow(TableColor);
            TableCol(ToCell(GetConst(Idx)));
            if Iface.HasDescriptions then
              TableCol(ToCell(GetShortName(Idx)));
            TableCol(ToCell(GetLongName(Idx)));
          EndTag;
        end;
      EndTag;
      Unindent;
    end;
    Unindent;
  end;
end;

procedure ExportContents(Iface: TMicexIface; Html: THtmlWriter);
var
  I, Y: Integer;
begin
  with Html, Iface do
  begin
    TaggedText('Содержание', [htH3]);
    HRef('Перечислимые типы', '#e');
    Writeln;
    Indent;
    for I := 0 to Types.Count - 1 do
      with Types[I] do
    begin
      HRef(Name + ' - ' + Caption, '#e' + Name);
      NewLine;
    end;
    Unindent;

    HRef('Таблицы', '#it');
    Writeln;
    Indent;
    for Y := 0 to Tables.Count - 1 do
      with Tables[Y] do
    begin
      HRef(Name + ' - ' + Caption, '#t' + IntToStr(Y));
      NewLine;
    end;

    Unindent;
    HRef('Транзакции', '#ir');
    Writeln;
    Indent;
    for Y := 0 to Transactions.Count - 1 do
      with Transactions[Y] do
    begin
      HRef(Name + ' - ' + Caption, '#r' + IntToStr(Y));
      NewLine;
    end;

    Unindent;
  end;
end;

procedure ExportDescToFile(Iface: TMicexIface; const FileName, Url: string);

  function GetMsgSetStr: string;
  begin
    if Iface.MsgSet <> '' then
      Result := ', msgset ' + Iface.MsgSet
    else
      Result := '';
  end;

var
  Html: THtmlWriter;
  IfaceObjects: string;
begin
  IfaceObjects := 'Объекты интерфейса ';
  Html := THtmlWriter.Create(FileName, htmlUtf8);
  with Html do
  try
    Head;
      TaggedText(IfaceObjects + Iface.Name, [htTitle]);
    EndTag;

    Body(clWhite);
//      Writeln('<font face="Arial Cyr, Arial, Verdana, Helvetica">');

      TaggedText(Format(IfaceObjects + '%s - %s%s',
        [Iface.Name, Iface.Caption, GetMsgSetStr]), [htH2]);
      Separator;

      ExportContents(Iface, Html);

      ExportEnums(Iface, Html);
      ExportIface(Iface, Html);

      Paragraph;
      Bookmark('refs');
      Writeln('<b>Жирным</b> шрифтом выделены ключевые поля.<br>' + sLineBreak +
              'Символом (*) помечены поля, содержащие код финансового инструмента.<br>' + sLineBreak +
              'Символом (+) помечены поля, которые могут повторяться в группе.');
      Separator;
      Writeln(Format('<font size=-1>Документ создан при помощи ASTSClient %s</font>',
        [DateTimeToStr(Now)]));

      Writeln('</font>');
    EndTag;
  finally
    Free;
  end;
end;

end.
